Remove specific class from group of elements without jquery

后端 未结 3 2067
独厮守ぢ
独厮守ぢ 2020-12-22 12:57

I have multiple span elements, I try to remove the class activeLang. How can I do this?

3条回答
  •  鱼传尺愫
    2020-12-22 13:38

    On modern, up-to-date browsers you can use forEach on the HTMLCollection (which inherits from NodeList) returned by querySelectorAll:

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

    On old browsers, you need to polyfill it, which you can do like this:

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

    You may also need a polyfill for classList.

    On truly obsolete browsers (IE8), you'd have to polyfill Array.prototype.forEach (and classList) first.

    Or use any of the "array-like" looping mechanism described in this answer.

提交回复
热议问题