Search code examples
javascriptdomnullinnerhtmlgetelementsbytagname

Can't use innerhtml or select nodes, returns null


After multiple hours of searching, I haven't found a solution to this yet. every time I run this code:

var output = document.getElementsByTagName('div');

var array = [];

for(var x = 0; x < output.length; x++){
    array.push(output[i])
    };

console.log(array);

all that I get in the console is:

[];

All I am trying to do is manipulate the inner html of one of the nodes (node #4 to be specific). I have also tried this:

var output = document.getElementsByTagName('div')[4];

output.innerHTML='hello world';

which just returns: Uncaught TypeError: Cannot set property 'innerHTML' of undefined. Any help would be much appreciated.

I should also mention that using querySelector or getElementById and targeting the specific div only returns null.


Solution

  • You're going to kick yourself.

    In your for loop, you are defining x as the iterator, but you are using output[i]. i hasn't been defined. Use output[x].

    Also, to get the fourth element, you want the element with index 3. Since indexing starts at zero, the first element would be 0. The fourth would be 3.