到目前为止,我必须这样做:

elem.classList.add("first");
elem.classList.add("second");
elem.classList.add("third");

这在jQuery中是可以实现的,就像这样

$(elem).addClass("first second third");

我想知道是否有任何本地的方法来添加或删除。


当前回答

我发现了一个非常简单的方法,更现代和优雅的方式。


const el = document.querySelector('.m-element');

// To toggle
['class1', 'class2'].map((e) => el.classList.toggle(e));

// To add
['class1', 'class2'].map((e) => el.classList.add(e));

// To remove
['class1', 'class2'].map((e) => el.classList.remove(e));

好在你可以很容易地扩展类数组或使用任何来自API的类数组。

其他回答

一个非常简单,不花哨,但有效的解决方案,我不得不相信是非常跨浏览器的:

创建这个函数

函数removeAddClasses(班级名册,removeCollection addCollection) { for (var i=0;i< removeccollection .length;i++){ classList.remove (removeCollection[我]); } for (var i=0;i<addCollection.length;i++){ classList.add (addCollection[我]); } }

这样叫它: removeAddClasses (node.classList arrayToRemove arrayToAdd);

...其中arrayToRemove是要删除的类名数组: (“myClass1”、“myClass2”)等等

...and arrayToAdd是一个要添加的类名数组: (“myClass3”、“myClass4”)等等

elem.classList.add("first");
elem.classList.add("second");
elem.classList.add("third");

是相等的

elem.classList.add("first","second","third");

向元素中添加类

document.querySelector(elem).className+=' first second third';

更新:

删除一个类

document.querySelector(elem).className=document.querySelector(elem).className.split(class_to_be_removed).join(" ");

新版本的DOMTokenList规范允许使用多个参数add()和remove(),以及第二个参数toggle()来强制状态。

在撰写本文时,Chrome支持添加()和删除()的多个参数,但其他浏览器都不支持。IE 10及以下、Firefox 23及以下、Chrome 23及以下及其他浏览器不支持toggle()的第二个参数。

我写了下面的小填充物来帮助我度过难关,直到支持扩展:

(function () {
    /*global DOMTokenList */
    var dummy  = document.createElement('div'),
        dtp    = DOMTokenList.prototype,
        toggle = dtp.toggle,
        add    = dtp.add,
        rem    = dtp.remove;

    dummy.classList.add('class1', 'class2');

    // Older versions of the HTMLElement.classList spec didn't allow multiple
    // arguments, easy to test for
    if (!dummy.classList.contains('class2')) {
        dtp.add    = function () {
            Array.prototype.forEach.call(arguments, add.bind(this));
        };
        dtp.remove = function () {
            Array.prototype.forEach.call(arguments, rem.bind(this));
        };
    }

    // Older versions of the spec didn't have a forcedState argument for
    // `toggle` either, test by checking the return value after forcing
    if (!dummy.classList.toggle('class1', true)) {
        dtp.toggle = function (cls, forcedState) {
            if (forcedState === undefined)
                return toggle.call(this, cls);

            (forcedState ? add : rem).call(this, cls);
            return !!forcedState;
        };
    }
})();

我们期望使用兼容ES5和DOMTokenList的现代浏览器,但我在几个特定的目标环境中使用了这个polyfill,所以它对我来说效果很好,但它可能需要调整脚本,以便在遗留的浏览器环境(如IE 8或更低版本)中运行。

在字符串中添加由空格分隔的多个类的更好方法是使用带有split的Spread_syntax:

element.classList.add(...classesStr.split(" "));