Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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).

like image 408
nCardot Avatar asked Jun 03 '18 22:06

nCardot


2 Answers

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]

like image 193
Cory Kleiser Avatar answered Oct 26 '22 23:10

Cory Kleiser


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)
like image 33
Get Off My Lawn Avatar answered Oct 27 '22 01:10

Get Off My Lawn