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:
That’s all there is to it.
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:
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:
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