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?
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?
Share Improve this question edited May 3, 2019 at 15:17 Cœur 38.8k25 gold badges205 silver badges277 bronze badges asked Jul 19, 2015 at 20:40 Richard BustosRichard Bustos 3,0185 gold badges27 silver badges32 bronze badges 2-
check if
dropdownList = document.getElementsByClassName('dropdown-list')
is returning[]
– vinayakj Commented Jul 19, 2015 at 20:42 -
In your 2 var declaration you have a
,
at the end instead of a;
– Zimmi Commented Jul 19, 2015 at 20:43
2 Answers
Reset to default 3document.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.
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')