Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript setattribute to multiple element

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");
like image 828
MathieuB Avatar asked Aug 27 '13 01:08

MathieuB


People also ask

Can you set multiple attributes in JavaScript?

To set multiple attributes for an element at once with JavaScript, we can call the element's setAttribute method. const setAttributes = (el, attrs) => { for (const [key, val] of Object.

What does setAttribute do in JavaScript?

Element.setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

How do I add multiple attributes in HTML?

Definition and Usage When present, it specifies that the user is allowed to enter more than one value in the <input> element. Note: The multiple attribute works with the following input types: email, and file. Tip: For <input type="file"> : To select multiple files, hold down the CTRL or SHIFT key while selecting.


1 Answers

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");
}
like image 154
Asad Saeeduddin Avatar answered Sep 19 '22 20:09

Asad Saeeduddin