Skip to content

Why is [0] needed for getElementsByClassName to work when there’s only one class to select?

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]