最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - classList.add() not working in a function? - Stack Overflow

programmeradmin5浏览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?

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
Add a ment  | 

2 Answers 2

Reset to default 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.

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')
发布评论

评论列表(0)

  1. 暂无评论