.getElementsByClassName()
returns a "live" node list. A node list is a generic term for a collection of nodes, which are the fundamental building blocks in the Document Object Model.
This collection/node list is an "array-like" object and can be iterated over.
But, .getElementsByClassName()
is a very old API and, as I mentioned, returns a "live" node list that causes the DOM to be re-scanned upon each access attempt to ensure that you always get the most up to date results. This can be useful in some edge cases where elements are being dynamically added or removed, but because of the fact the the DOM is re-scanned every time you access it, it can hurt performance dramatically and therefore should rarely, if ever, be used.
The lines of code you shared:
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
don't show you using what's returned by .getElementsByClassName()
, the second line is accessing one of the individual nodes within the node list (the first one to be exact) and that individual node is what .innerHTML
is being called on.
Now, those lines are absolutely terrible lines from a performance standpoint because if you are only interested in the first match in the collection, you shouldn't scan the whole DOM and then just use only the first match. Instead, just search for the first match with .querySelector()
.
Additionally, don't use .innerHTML
when the string you are working with doesn't contain any HTML as .innerHTML
has security and performance implications.
W3 Schools is very well known as being a very poor resource to use as the content there is very often outdated, incomplete, or flat out wrong. Instead use one of the most trusted authorities on web development, The Mozilla Developers Network.
The modern replacement for it is .querySelectorAll()
, which you can pass any valid CSS selector into and it returns a static node list. If you need to update the list, you can just call it again as needed.
So, with all that said, the better way to accomplish what the two lines you shared do is this:
// Find the first node that has the example class and
// set its text to "Hello World!"
var x = document.querySelector(".example").textContent = "Hello World!";