KAROUMI
KAROUMI

Reputation: 11

fix cannot set property 'innerHTML' of undefined when using getElementsByClassName

for(i = 0; i <= document.getElementsByClassName("contC").length; i++){ 
    document.getElementsByClassName("contC")[i].innerHTML = "aaa";
};

Upvotes: 1

Views: 342

Answers (4)

twharmon
twharmon

Reputation: 4272

The error is that you need < instead of <= in your for loop. If document.getElementsByClassName("contC").length is 5, then document.getElementsByClassName("contC")[5] is undefined, 4 would be the last index.

This works fine:

for(i = 0; i < document.getElementsByClassName("contC").length; i++){ 
    document.getElementsByClassName("contC")[i].innerHTML = "aaa";
};

No need, however, to call document.getElementsByClassName twice:

const els = document.getElementsByClassName("contC")
for (let i = 0; i < els.length; i++) { 
    els[i].innerHTML = "aaa";
}

or:

const els = document.getElementsByClassName("contC")
Array.from(els).forEach(e => e.innerHTML = "aaa")

Upvotes: 1

Nicolas
Nicolas

Reputation: 8650

The exit condition of your for loop is incorrect. You are checking whether or not the i variable is smaller OR EQUALS to the length of your array. But, since the array index starts at 0, the array[array.length] position does not exists ( it goes from 0 to array.length - 1. Hense why you are getting this error.

for(let i = 0; i < document.getElementsByClassName("contC").length; i++){ 
    document.getElementsByClassName("contC")[i].innerHTML = "aaa";
};

Below is an improved version of you code. Here is what i've changed.

  • I've use the let keyword in order to initialize the variable correctly.
  • i've saved the HTML node into an array instead of ready the whole document at each iteration.
  • I've removed the semi-colon after the closing bracket of the for loop as it is not necessary.
const nodes = document.getElementsByClassName("contC");
for(let i = 0; i < nodes.length; i++){ 
    nodes[i].innerHTML = "aaa";
}

Upvotes: 0

Arturas
Arturas

Reputation: 202

Try to use for of loop like:

for (let elem of document.getElementsByClassName("contC")) {
  elem.innerHTML = "aaa";
}

Upvotes: 0

elvira.genkel
elvira.genkel

Reputation: 1333

Your loop iterate from 0 to collection lenght. It is necessary to iterate to document.getElementsByClassName("contC").length - 1 or change condition from <= to < While condition is <= last element is out of range of collection. If collection has 4 elements indexes are 0...3, collection[4] is out of range

for(i = 0; i <= document.getElementsByClassName("contC").length - 1; i++){ 
    document.getElementsByClassName("contC")[i].innerHTML = "aaa";
};
<div class='contC'></div>
<div class='contC'></div>
<div class='contC'></div>
<div class='contC'></div>

Upvotes: 0

Related Questions