我有很多
publish_0
类的 div,我想通过单击按钮将其更改为 publish_1
。
现在我使用这个,但它只改变了一项。
如何将 setattribute 应用到所有具有
publish_0
的项目。
document.querySelector('.publish_0').setAttribute("class", "publish_1");
您需要使用循环来迭代所有元素并单独设置它们的类属性值:
var els = document.querySelectorAll('.publish_0');
for (var i=0; i < els.length; i++) {
els[i].setAttribute("class", "publish_1");
}
当您无法使用 jQuery 但想要类似的便利时,您可以执行以下操作。将以下代码添加到文件顶部或其他容易看到的位置。
NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;
现在在您的代码中您可以执行以下操作:
document.querySelectorAll('body,main,article,[class*=content],[class*=center]')
.forEach((function(x){ x.setAttribute("style","width:1920px");}))
或者更好的是,如果浏览器支持 ECMAScript2015,您可以使用箭头语法:
document.querySelectorAll('[class*=content]')
.forEach( x=> x.setAttribute("style","width:1200px"))
如果您愿意,可以将所有声明放在一行中。
我使用 Vanilla JS for…of 循环。
在我看来,这是比 @Asad Saeeduddin 的 和 @Derek Ziemba 的 答案中的语法更直观的语法。
Unicorn代码风格检查器更喜欢
for…of
而不是forEach()
方法。 no-array-for-each
独角兽的规则:
语句相对于for…of
方法的好处包括:forEach
- 更快
- 更好的可读性
- 能够通过
提早退出或break
return
此外,如果您使用 TypeScript,使用
有很大好处,因为它不会导致跨越函数边界。这意味着当前作用域中较早的类型缩小将在循环内部正常工作(无需重新类型缩小)。此外,循环内的任何变异变量都将被拾取,以便确定变量是否正在使用。for…of
<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
按钮后,将所有具有 .publish_1
类的元素的类 .publish_0
更改为 Change the class for multiple elements!
:
for…of
caniuse.com 上的声明:
Safari 自 2013 年起支持
for…of
,Chrome 和 Opera 自 2014 年起支持,Edge 自 2015 年起支持,Firefox 自 2017 年起支持。
此答案截至 2024 年 2 月有效。将来,我的答案的数据可能会过时。
您可以将其与 jquery 一起使用:
$(".publish_0").attr("class", "publish_1")
或者,使用 getElementsByClassName 并循环返回的 DOM 元素。