DEV Community

David Frempong
David Frempong

Posted on

How I target an Element By Class Name in JavaScript

This concept deals with the classes you create in HTML.

IF I want to target a specific class in JavaScript, I'll do something like this first in HTML:
<div class="next"></div>

That is my HTML class. And in JavaScript,

document.getElementsByClassName('next')[0]

You want the document, or DOM, to "get" the element by it's class name in HTML. But why did I add that 0 with the brackets like this [0]?

Each class is listed as an array, or group of items. So to choose the one I want, I simply choose the specific "index" in the array which is equal to the class I'm trying to target.

This is one way you can target an HTML class in JavaScript.

Top comments (7)

Collapse
 
jamesthomson profile image
James Thomson

But why did I add that 0 with the brackets like this [0]?

If you use querySelector you won't have to do this as it returns the first matched element. getElementByClassName is a good starting point for new developers, but once familiar with selecting elements I'd say querySelector (and it's companion querySelectorAll) is preferable as it allows for more advanced selectors such as a[href*='dev.to'].

Collapse
 
ricobrase profile image
Rico Brase

Please note, that querySelectorAll and getElementsByClassName behave quite differently - querySelectorAll returns a static NodeList, getElementsByClassName returns a HTMLCollection.

From the MDN:

An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed. For this reason it is a good idea to make a copy (eg. using Array.from) to iterate over if adding, moving, or removing nodes.

If you were aware of this and specifically require those live updates from the HTMLCollection, you can't use querySelectorAll.

Collapse
 
jamesthomson profile image
James Thomson

This is a very good point and a good use case in favour of getElementsByClassName should you need changes to the selected DOM elements to persist.

Collapse
 
davidfrempong profile image
David Frempong

Good point.

Collapse
 
codingjlu profile image
codingjlu

document.getElementsByClassName

Collapse
 
liviufromendtest profile image
Liviu Lupei • Edited

I think you have a typo.
Isn't it supposed to be getElementsByClassName?
Instead of getElementByClassName.

Collapse
 
davidfrempong profile image
David Frempong

Yes it is. Thanks.