I tried using let modal = document.getElementsByClassName('modal')
to select an element with the class modal
. It only worked after using node selection to select the first result: let modal = document.getElementsByClassName('modal')[0]
. I know the method Document.getElementsByClassName()
returns child elements which have all of the given class names, but there's only one element in my HTML with that class. I confirmed this in my browser's dev tools by using var x = document.getElementsByClassName('modal').length
and logging the value of x to the console (it returned 1 as expected).
Could someone explain why node selection is needed in this case?
Edit: My question is different than the one marked as a duplicate. In that question, they are asking the difference between methods than return a single element and those that return an array-like collection of elements. I'm already aware getElementsByClassName
returns an array-like collection of elements, whereas the other methods return one element. My question is why do you need to specify the index in a case where all elements of a class are returned but there's only one element with a class (so one item, the correct item, is returned).
document.getElementsByClassName
will return a list of elements with the given class name. Even if there is only one element with that class name it will be in a Node List which is why you have to use the [0]
It is needed because getElementsByClassName Returns an HTMLCollection and not a single element.
To get the item without using [0]
, use a query selector instead, this will give you the item instead of a collection of items.
let modal = document.querySelector('.modal')
console.log(modal)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With