17

I have many div with the class publish_0 that I would like to change to publish_1 on click of a button.

Right now I use this but it only change one item.

How to I apply the setattribute to all item that have the publish_0.

document.querySelector('.publish_0').setAttribute("class", "publish_1");
TylerH
  • 20,799
  • 66
  • 75
  • 101
MathieuB
  • 505
  • 2
  • 8
  • 20

3 Answers3

44

You need to use a loop to iterate over all the elements and set their class attribute value individually:

var els = document.querySelectorAll('.publish_0');
for (var i=0; i < els.length; i++) {
    els[i].setAttribute("class", "publish_1");
}
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • 4
    As you are using a class you can use `getElementsByClassname` instead of `querySelectorAll`, it's performing way better. See an example [here](https://jsperf.com/getelementsbyclassname-vs-queryselectorall/2) – sirLisko Jun 11 '15 at 14:10
15

For when you can't use jQuery but want the convenience of something similar, you can do the following. Add the following code to the top of the file or somewhere else easily visible.

NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;

Now in your code you can do this:

document.querySelectorAll('body,main,article,[class*=content],[class*=center]')
        .forEach((function(x){ x.setAttribute("style","width:1920px");}))

Or even nicer yet, if the browser supports ECMAScript2015 you can use arrow syntax:

document.querySelectorAll('[class*=content]')
        .forEach( x=> x.setAttribute("style","width:1200px"))

You can put the statement all on one line if you'd like.

Derek Ziemba
  • 2,467
  • 22
  • 22
-4

You can use this with jquery:

$(".publish_0").attr("class", "publish_1")

Alternatively, use getElementsByClassName and loop through the DOM elements returned.

Vivek
  • 428
  • 2
  • 13
  • 3
    Vivek, while I appreciate your suggestion of using jQuery, the OP has expressed their question with respect to Vanilla JavaScript. Please consider this for future answers. – Eliseo D'Annunzio Feb 18 '21 at 22:16