0

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?

2
  • check if dropdownList = document.getElementsByClassName('dropdown-list') is returning [] Commented Jul 19, 2015 at 20:42
  • In your 2 var declaration you have a , at the end instead of a ; Commented Jul 19, 2015 at 20:43

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.