Uncaught TypeError: Can not set property 'text' of undefined

0

I am trying to generate a random for a test site but I see that my script crashes with other elements by the method .text of the transaction and throws me the error:

Uncaught TypeError: Cannot set property 'text' of undefined

Any suggestions to solve it?

// Random para imprimir el id de la transacción.
var middle = ['123','2345','3456','3456','5','67890','9877','89878','8989','1010',],
  sufix = ['Ab','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

  var random = function(){
      return Math.floor(Math.random() * 3) 
};

var idTansaction =  'Order Id \n '+ middle[random()] + sufix[random()];


console.log("Transaccion numero = " + idTansaction);
document.getElementsByTagName("h2")[1].text = idTansaction;

  if (page[page.length-1] === success_page) {

      dataLayer.push({
        'event':'purchase',
          'ecommerce': {
            'purchase': {
                'actionField': {
                  'id': idTansaction, // Transaction ID. Required for purchases and refunds.
                  'affiliation': 'Online Store',
                  'revenue': totalTransaccion, // Total transaction value (incl. tax and shipping)
                  'tax': tax,
                  'shipping': '',
                  'coupon': couponString
                },
               'products': cartItems
            }
          }
        });


      localStorage.clear();
  }
    
asked by Oscar iyañez 18.07.2017 в 01:00
source

1 answer

2

It's because the H1..H6 elements do not have the text attribute, instead it uses innerHTML

var idTansaction = 123;
//No existe .text
document.getElementsByTagName("h2")[0].text = idTansaction;
//asignado con .innerHTML
document.getElementsByTagName("h2")[1].innerHTML = idTansaction;
<h2>Titulo</h2>
<h2>Titulo</h2>
    
answered by 18.07.2017 в 01:34