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)
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 sayquerySelector
(and it's companionquerySelectorAll
) is preferable as it allows for more advanced selectors such asa[href*='dev.to']
.Please note, that
querySelectorAll
andgetElementsByClassName
behave quite differently -querySelectorAll
returns a staticNodeList
,getElementsByClassName
returns aHTMLCollection
.From the MDN:
If you were aware of this and specifically require those live updates from the
HTMLCollection
, you can't usequerySelectorAll
.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.Good point.
document.getElementsByClassName
I think you have a typo.
Isn't it supposed to be getElementsByClassName?
Instead of getElementByClassName.
Yes it is. Thanks.