javascript setattribute 到多个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18455353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript setattribute to multiple element
提问by MathieuB
I have many div with the class publish_0
that I would like to change to publish_1
on click of a button.
我有很多 div publish_0
,我想publish_1
通过单击按钮将其更改为该类。
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
.
如何将 setattribute 应用于所有具有publish_0
.
document.querySelector('.publish_0').setAttribute("class", "publish_1");
采纳答案by Vivek
You can use this with jquery:
您可以将其与 jquery 一起使用:
$(".publish_0").attr("class", "publish_1")
Alternatively, use getElementsByClassName and loop through the DOM elements returned.
或者,使用 getElementsByClassName 并遍历返回的 DOM 元素。
回答by Asad Saeeduddin
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");
}
回答by Derek Ziemba
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.
当您不能使用 jQuery 但想要类似的便利时,您可以执行以下操作。将以下代码添加到文件顶部或其他容易看到的地方。
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:
或者更好的是,如果浏览器支持 ECMAScript2015,您可以使用箭头语法:
document.querySelectorAll('[class*=content]')
.forEach( x=> x.setAttribute("style","width:1200px"))
You can put the statement all on one line if you'd like.
如果您愿意,可以将所有语句放在一行中。