[英]classList.add() not working in a function?
classList not working as expected classList无法正常工作
var button = document.getElementById('dropdown-trigger'),
dropdownList = document.getElementsByClassName('dropdown-list'),
button.addEventListener('mouseover', displayDropdown);
function displayDropdown() {
dropdownList.classList.add('none');
}
I keep getting in the console: 我一直进入控制台:
Uncaught TypeError: Cannot read property 'add' of undefined 未捕获的TypeError:无法读取未定义的属性“ add”
But if I were to use classList like: 但是如果我像这样使用classList:
function displayDropdown() {
button.classList.add('none');
}
It would work just fine. 它将正常工作。 It seems like I can't use classlist on other elements? 看来我不能在其他元素上使用classlist?
document.getElementsByClassName
returns a list of elements, not a single element (hence the 'element s '). document.getElementsByClassName
返回元素列表,而不是单个元素(因此为'element s ')。 You'll want to add the class on each of these elements. 您需要在每个这些元素上添加类。 If there's only a single dropdown list, you could also give it an ID and use getElementById
instead. 如果只有一个下拉列表,则还可以为其指定一个ID并使用getElementById
代替。
It seems like I cant use classlist on other elements. 看来我不能在其他元素上使用classlist。
You can, but not on a NodeList
collection. 您可以,但不能在NodeList
集合上。 You should either iterate through the collection or get a specific item from the collection. 您应该遍历集合或从集合中获取特定项。
dropdownList[0].classList.add('none');
Another option is using the querySelector
method instead of the getElementsByClassName
. 另一种选择是使用querySelector
方法而不是getElementsByClassName
。 querySelector
function selects the first matching element. querySelector
函数选择第一个匹配的元素。
dropdownList = document.querySelector('.dropdown-list')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.