如何在没有jQuery的情况下向元素添加类?

时间:2021-08-02 08:28:21

How do I add the class name "foo" to the root <html> element without using jQuery (or a similar library)?

如何在不使用jQuery(或类似库)的情况下将类名“foo”添加到根元素中?

3 个解决方案

#1


60  

Just get the element and append to the list of classes.

只需获取元素并附加到类列表即可。

document.documentElement.className += " foo";

#2


47  

You can use the classList to access an element's list of classes.

您可以使用classList访问元素的类列表。

document.documentElement.classList.add('my-awesome-class');

document.documentElement.classList.remove('my-awesome-class');

document.documentElement.classList.contains('my-awesome-class');

#3


5  

AddClass(document.documentElement, 'my-awesome-class', true); //add
AddClass(document.documentElement, 'my-awesome-class', false); //remove

function AddClass(o,c,bAdd){
    var list = o.className.split(" ");
    if (list.indexOf(c)!==-1){
        if (!bAdd) delete list[list.indexOf(c)];
    }else{
        if (bAdd) list[list.length] = c;
    }
    o.className = list.join(" ");
}

#1


60  

Just get the element and append to the list of classes.

只需获取元素并附加到类列表即可。

document.documentElement.className += " foo";

#2


47  

You can use the classList to access an element's list of classes.

您可以使用classList访问元素的类列表。

document.documentElement.classList.add('my-awesome-class');

document.documentElement.classList.remove('my-awesome-class');

document.documentElement.classList.contains('my-awesome-class');

#3


5  

AddClass(document.documentElement, 'my-awesome-class', true); //add
AddClass(document.documentElement, 'my-awesome-class', false); //remove

function AddClass(o,c,bAdd){
    var list = o.className.split(" ");
    if (list.indexOf(c)!==-1){
        if (!bAdd) delete list[list.indexOf(c)];
    }else{
        if (bAdd) list[list.length] = c;
    }
    o.className = list.join(" ");
}