我有多个span元素,我尝试删除该类activeLang。我怎样才能做到这一点?
<div class="header_content_lang">
<span class="langNav">
...
</span>
<span class="langNav">
...
</span>
<span class="langNav activeLang">
...
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
我这样尝试过,就像这里建议的那样:
var x = document.getElementsByClassName(".activeLang");
[].forEach.call(x, function(el) {
el.classList.remove(".activeLang");
});
console.log(x[0]);
console.log(x[1]);
console.log(x[2]);
Run Code Online (Sandbox Code Playgroud)
但所有日志的输出都是“未定义”的。
在现代的、最新的浏览器上,您可以使用forEach由返回的HTMLCollection(继承自NodeList)querySelectorAll:
document.querySelectorAll(".activeLang").forEach(function(element) {
element.classList.remove("activeLang");
});
Run Code Online (Sandbox Code Playgroud)
在旧浏览器上,您需要对其进行填充,可以这样做:
if (!NodeList.prototype.forEach) {
Object.defineProperty(NodeList.prototype, "forEach", {
value: Array.prototype.forEach
});
}
Run Code Online (Sandbox Code Playgroud)
您可能还需要一个polyfill classList。
在真正过时的浏览器(IE8)上,您必须首先填充Array.prototype.forEach(和classList)。
或者使用此答案中描述的任何“类似数组”的循环机制。
| 归档时间: |
|
| 查看次数: |
4506 次 |
| 最近记录: |