javascript setattribute to multiple element

后端 未结 3 1044
梦毁少年i
梦毁少年i 2020-12-05 11:31

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 ch

3条回答
  •  死守一世寂寞
    2020-12-05 12:08

    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.

提交回复
热议问题