简体   繁体   中英

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?

In case it's something in my code, here's my CodePen .

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

将返回具有此类的元素数组

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM