Reputation: 3018
classList not working as expected
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
But if I were to use classList like:
function displayDropdown() {
button.classList.add('none');
}
It would work just fine. It seems like I can't use classlist on other elements?
Upvotes: 0
Views: 9559
Reputation: 144739
It seems like I cant use classlist on other elements.
You can, but not on a NodeList
collection. 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
function selects the first matching element.
dropdownList = document.querySelector('.dropdown-list')
Upvotes: 2
Reputation: 19695
document.getElementsByClassName
returns a list of elements, not a single element (hence the 'elements'). 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.
Upvotes: 3