MathieuB
MathieuB

Reputation: 527

How to use JavaScript's setattribute to affect multiple elements?

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");

Upvotes: 18

Views: 51146

Answers (4)

Саша Черных
Саша Черных

Reputation: 2823

1. My choice

I use Vanilla JS for…of loops.

2. Advantages

  1. In my opinion, this is a more intuitive syntax than the syntax in @Asad Saeeduddin’s and @Derek Ziemba’s answers.

  2. Unicorn code style checker prefers for…of to forEach() method. no-array-for-each Unicorn’s rule:

    Benefits of for…of statement over the forEach method can include:

    1. Faster
    2. Better readability
    3. Ability to exit early with break or return

    Additionally, using for…of has great benefits if you are using TypeScript, because it does not cause a function boundary to be crossed. This means that type-narrowing earlier on in the current scope will work properly while inside of the loop (without having to re-type-narrow). Furthermore, any mutated variables inside of the loop will picked up on for the purposes of determining if a variable is being used.

3. MCVE

Live demonstration on LiveCodes:

<button>Change the class for multiple elements!</button>

<div class="publish_0">Kira Amazing!</div>

<div class="publish_0">Kira Goddess!</div>

<div class="publish_0">Kira Incredible!</div>

$KiraMarginBottom
    margin-bottom 1rem

button
    @extend $KiraMarginBottom

.publish_0
    background-color yellow
    @extend $KiraMarginBottom

.publish_1
    background-color pink
    @extend $KiraMarginBottom
    
kiraButton = document.querySelector("button")

kiraChangeClassByClickForMultipleElements = ->

    kiraElementsNeedingClassChanges = document.querySelectorAll(".publish_0")

    for kiraElementInNeedOfClassChange from kiraElementsNeedingClassChanges

        ###
        [INFO] Or use “classList” or “className” properties:
        https://stackoverflow.com/a/196038/5951529
        https://stackoverflow.com/a/196016/5951529

        [INFO] “setAttribute()” method also works. I left it to make it clearer how to add attributes:
        https://stackoverflow.com/a/8428872/5951529
        ###
        kiraElementInNeedOfClassChange.setAttribute "class", "publish_1"

        console.log(kiraElementInNeedOfClassChange.className)

kiraButton.addEventListener "click", kiraChangeClassByClickForMultipleElements

.publish_0 class

The code above changes the class .publish_0 to .publish_1 for all elements with the class .publish_0 after clicking or pressing the Change the class for multiple elements! button:

.publish_1 class

4. Browser compatibility

for…of statement on caniuse.com:

for…of on CanIUse

Safari supports for…of since 2013, Chrome and Opera since 2014, Edge since 2015 and Firefox since 2017.

5. Relevance of the answer

This answer is relevant as of February 2024. In the future, data of my answer may be obsolete.

Upvotes: 0

Derek Ziemba
Derek Ziemba

Reputation: 2643

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.

Upvotes: 16

user1726343
user1726343

Reputation:

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");
}

Upvotes: 44

Vivek
Vivek

Reputation: 428

You can use this with jquery:

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

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

Upvotes: -4

Related Questions