+6 votes
by (13.6m points)

I need to add a class to bulk of <a> tag. I have to select the a tag using querySelectorAll method, and all elements are selected. But when I trying to add a class to them it won't added.

I have try the following example.

var qc=document.querySelectorAll(".Label ul li a");
qc.className+="newcls";

https://jsfiddle.net/ahhvovvv/

But I can add it through jQuery, but don't use jQuery.
The working jQuery code is

$(document).ready(function(){

   $(".Label ul li a").addClass("newcls");

});

3 Answers

+6 votes
by (13.6m points)

I'd suggest:

// converts the collection of elements returned from
// document.querySelectorAll() into an Array, using
// Array.from(), then iterates over that Array using
// Array.prototype.forEach():
Array.from( document.querySelectorAll(".Label ul li a") ).forEach(

  // using arrow function syntax to perform the same
  // action on each <a> ('aElement') within the
  // array; here using Element.classList API to
  // add the given class-name:
  aElement => aElement.classList.add('newClass')
);
+5 votes
by (13.6m points)

You have to iterate through the Collection, one way could be:

var qc = document.querySelectorAll(".Label ul li a");
[].forEach.call(qc, function(item) {
    item.className+=" newcls";
})

Fiddle updated

Remember to add a space before the class if you'll use className , since you are editing the whole class , otherwise you could use

item.classList.add('newcls');
+1 vote
by (13.6m points)

In your code qc is collection. You should iterate through it. And className is not a collection it is a string where class names separated with space. So here is your code fixed

var qc=document.querySelectorAll(".Label ul li a");
for(var i=0; i<qc.length; i++) {
    qc.classList.add("newcls");
    //replace with next line if you need this working in IE before version 10 
    //qc.item(i).className+=" newcls";
}
...