gpt4 book ai didi

javascript - 不使用 jquery 从元素组中删除特定类

转载 作者:行者123 更新时间:2023-11-28 04:07:40 26 4
gpt4 key购买 nike

我有多个 span 元素,我尝试删除 activeLang 类。我怎样才能做到这一点?

<div class="header_content_lang">
<span class="langNav">
...
</span>
<span class="langNav">
...
</span>
<span class="langNav activeLang">
...
</span>
</div>

我这样尝试过,就像建议的那样here :

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

但是所有日志的输出都是“未定义”的。

最佳答案

在现代的最新浏览器上,您可以使用 forEachquerySelectorAll 返回的 HTMLCollection(继承自 NodeList)上:

document.querySelectorAll(".activeLang").forEach(function(element) {
element.classList.remove("activeLang");
});

在旧浏览器上,您需要对其进行填充,可以这样做:

if (!NodeList.prototype.forEach) {
Object.defineProperty(NodeList.prototype, "forEach", {
value: Array.prototype.forEach
});
}

您可能还需要classList的polyfill .

在真正过时的浏览器(IE8)上,您必须填充 Array.prototype.forEach (和classList)首先。

或者使用任何描述的“类数组”循环机制 in this answer .

关于javascript - 不使用 jquery 从元素组中删除特定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com