Reputation: 7025
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?
Upvotes: 0
Views: 2740
Reputation: 5845
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);
}
Upvotes: 2