How to modify style to HTML elements (styled externally with CSS) using JS?

Others have suggested .getElementsByClassName("home")[0], which is a terrible idea.

First, .getElementsByClassName() returns a node list of all the matching elements. If you are only interested in the first one, it makes no sense to find that one and then keep scanning for more matches and then discard all but the first one found, which is what this code does.

Second, .getElementsByClassName() returns a “live” node list. This means that every time you interact with the list, the entire DOM is searched again for matches, ensuring that you have the most up to date set in your list. This can be useful in applications where nodes are being added and removed dynamically, but those use cases aren’t as common.

FYI: .getElementsByTagName(), .getElementsByName(), and node.childNodes also return live node lists.

All of these previously mentioned methods date back to the earliest days of the DOM API, when it was still the “wild west” days of web development. They are all over two decades old and have much better alternatives today (i.e. .querySelector(), .querySelectorAll(), .closest()).

When it’s not necessary to keep an up to date list, .querySelectorAll() is the way to go. And frankly, even if you do need an updated node list, you’re still better off with .querySelectorAll() and just run it again manually at the point where you need an updated list.

Here’s a good page that discusses this and here’s what it has to say:

How to Think About Live Object?

Live object is not intuitive. You can think of it as delayed
evaluation or lazy evaluation. Method or property of live object is
re-computed when their result is accessed.


But, in this case, we don’t even want a node list, we just want a single node. The correct solution would be:

document.querySelector(".home");

.querySelector() scans the document for the first element that matches the supplied selector and, if found, returns a reference to that single node. Otherwise, it returns undefined.

Leave a Comment