0

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?

1
  • 1
    querySelectorAll, as the name implies, returns a collection of elements. The collection doesn't have a classList property. Commented May 3, 2014 at 19:18

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This actually is more of what I need to do.

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.