简体   繁体   中英

Error when using .classList.add

I'm playing around with .classList and I'm getting some odd errors in my console. Here's my demo

Basically, I have an array of images all with the class of child and I'm doing a javascrpt .querySelectorAll to store those images in a variable for further manipulation.

var el = document.querySelectorAll('.child');

console.log(el.classList;);
el.classList.add("someClass");

But when I open up my console I'm getting some errors .

This one in reference to .classList; undefined And this one in reference to .classList.add();

 Uncaught TypeError: Cannot read property 'add' of undefined 

Yet, when I switch to looking up elements by ID, the errors go away. Now using IDs isn't out of the question, but ideally I'd like to keep things to class Names. Any idea what's going on?

el is a collection, not a single DOM element. classList does not make much sense for an array, though. So what you might want to do:

var product = document.getElementsByClassName('product');
var el = document.querySelectorAll('.child');
for(var i = 0; i < el.length; i++) {
    el[i].classList.add("someClass");
    console.log(el[i].classList);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM