getElementsByClassName innerHTML

TL;DR Summary – getElementsByClassName innerHTML

There are three ways you can go about either setting or reading getElementsByClassName innerHTML values: the good, the bad & the ugly.

1) The Good

Best way to go about getting all elements by class name is by not using getElementsByClassName function at all. The reason is that the returned object is not an array but HTMLCollection instead. Which means you will have all kind of headaches working with that object.

Instead use querySelectorAll function and your life will be much easier. Full code is below:

<div class="myclass">text one</div>
<div class="myclass">text two</div>
<div class="myclass">text three</div>

  const elements = document.querySelectorAll('.myclass');

  elements.forEach((el, index) =>{
    // reading innerHTML
    // writing to innerHTML
    el.innerHTML = `<i>changed text - ${index}</i>`;

That’s all there is to it.

More Details

Now if you still want to mess with the  getElementsByClassName function then you can use one of the next two methods:

2) The Bad

Trick to this method is ti transform the collection you got using getElementsByClassName function and transform it into regular looking array:

// replace this line
const elements = document.querySelectorAll('.myclass');

// with these two lines
const elementsCollection = document.getElementsByClassName('myclass');
const elements = Array.from(elementsCollection);

And now your previous code will work the same as before.

3) The Ugly

Third option is to use HTMLCollection that you got from getElementsByClassNamefunction directly.

And here you can no longer use forEach function and you have to do a for loop with helper variables.

Snippet of code is worth a thousand words so take a look yourself:

const elements = document.getElementsByClassName('myclass');

for (let i = 0; i < elements.length; i++) {
  // reading innerHTML
  // writing to innerHTML
  elements[i].innerHTML = `<i>changed text - ${i}</i>`;

And this is all there is to using¬†getElementsByClassName innerHTML¬†with it’s benefits and pitfalls.

Also, make sure to check out the article about img onclick behavior.

Until next time,
Senior Developer Content Writer