使用JavaScript(没有jQuery)从元素中删除CSS类[duplicate]

时间:2022-11-22 23:07:02

This question already has an answer here:

这个问题已经有了答案:

Could anyone let me know how to remove a class on an element using JavaScript only? Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.

有没有人能让我知道如何只使用JavaScript删除一个元素上的类?请不要用jQuery给我一个答案,因为我不能用它,我也不知道。

13 个解决方案

#1


755  

The right and standard way to do it is using classList. It is now widely supported in the latest version of most modern browsers:

正确和标准的方法是使用classList。目前,大多数现代浏览器的最新版本都广泛支持它:

ELEMENT.classList.remove("CLASS_NAME");

Documentation: https://developer.mozilla.org/en/DOM/element.classList

文档:https://developer.mozilla.org/en/DOM/element.classList

#2


500  

document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/,'');

where MyID is the ID of the element and MyClass is the name of the class you wish to remove.

其中MyID是元素的ID, MyClass是要删除的类的名称。


UPDATE: To support class names containing dash character, such as "My-Class", use

更新:要支持包含破折号字符的类名,如“My-Class”,请使用

document.getElementById("MyID").className =
  document.getElementById("MyID").className
    .replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');

#3


52  

Here's a way to bake this functionality right into all DOM elements:

这里有一种方法,可以将此功能整合到所有DOM元素中:

HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName;
}

#4


38  

function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }

#5


30  

div.classList.add("foo");
div.classList.remove("foo");

More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList

更在https://developer.mozilla.org/en-US/docs/Web/API/element.classList

#6


24  

Edit

编辑

Okay, complete re-write. It's been a while, I've learned a bit and the comments have helped.

好的,完全的重写。已经有一段时间了,我学到了一些东西,这些评论对我很有帮助。

Node.prototype.hasClass = function (className) {
    if (this.classList) {
        return this.classList.contains(className);
    } else {
        return (-1 < this.className.indexOf(className));
    }
};

Node.prototype.addClass = function (className) {
    if (this.classList) {
        this.classList.add(className);
    } else if (!this.hasClass(className)) {
        var classes = this.className.split(" ");
        classes.push(className);
        this.className = classes.join(" ");
    }
    return this;
};

Node.prototype.removeClass = function (className) {
    if (this.classList) {
        this.classList.remove(className);
    } else {
        var classes = this.className.split(" ");
        classes.splice(classes.indexOf(className), 1);
        this.className = classes.join(" ");
    }
    return this;
};


Old Post
I was just working with something like this. Here's a solution I came up with...

// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
    Object.defineProperty(String.prototype,'trim', {
        value: function() {
            return this.replace(/^\s+|\s+$/g,'');
        },
        writable:false,
        enumerable:false,
        configurable:false
    });
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
    value: function(c) {
        if(this.className.indexOf(c)<0) {
            this.className=this.className+=' '+c;
        }
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double 
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
    value: function(c) {
        this.className=this.className.replace(c,'').replace('  ',' ').trim();
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});

Now you can call myElement.removeClass('myClass')

现在你可以调用骨髓元素。removeclass(“myClass”)

or chain it: myElement.removeClass("oldClass").addClass("newClass");

或链:myElement.removeClass(oldClass).addClass(“终极”);

#7


15  

It's very simple, I think.

我认为这很简单。

document.getElementById("whatever").classList.remove("className");

#8


8  

try:

试一试:

function removeClassName(elem, name){
    var remClass = elem.className;
    var re = new RegExp('(^| )' + name + '( |$)');
    remClass = remClass.replace(re, '$1');
    remClass = remClass.replace(/ $/, '');
    elem.className = remClass;
}

#9


4  

var element = document.getElementById('example_id');
var remove_class = 'example_class';

element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');

#10


2  

All of these answers are way too complicated, try

所有这些答案都太复杂了,试试看

var string = "Hello, whats on your mind?";
var new_string = string.replace(', whats on your mind?', '');

The result would be a return of the string

结果将是字符串的返回。

Hello

Super easy. Credits go to jondavidjohn Remove portion of string in Javascript

超级简单。请将Javascript中的字符串部分删除到jondavidjohn

#11


1  

I use this JS snippet code :

我使用这个JS代码片段:

First of all, I reach all the classes then according to index of my target class, I set className = "".

首先,我到达所有的类,然后根据我的目标类的索引,设置className = ""。

Target = document.getElementsByClassName("yourClass")[1];
Target.className="";

#12


-3  

There is also $.toggleClass, $.addClass, and $.removeClass. For documentation, take a look at http://api.jquery.com/toggleClass/.

还有美元。toggleClass,美元。addClass,.removeClass美元。有关文档,请查看http://api.jquery.com/toggleClass/。

Take a look at this jsFiddle example to see it in action.

看看这个jsFiddle示例,就可以看到它的作用。

#13


-5  

document.getElementById("whatever").className += "classToKeep";

With the plus sign ('+') appending the class as opposed to overwriting any existing classes

使用加号('+')附加类,而不是覆盖任何现有类

#1


755  

The right and standard way to do it is using classList. It is now widely supported in the latest version of most modern browsers:

正确和标准的方法是使用classList。目前,大多数现代浏览器的最新版本都广泛支持它:

ELEMENT.classList.remove("CLASS_NAME");

Documentation: https://developer.mozilla.org/en/DOM/element.classList

文档:https://developer.mozilla.org/en/DOM/element.classList

#2


500  

document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/,'');

where MyID is the ID of the element and MyClass is the name of the class you wish to remove.

其中MyID是元素的ID, MyClass是要删除的类的名称。


UPDATE: To support class names containing dash character, such as "My-Class", use

更新:要支持包含破折号字符的类名,如“My-Class”,请使用

document.getElementById("MyID").className =
  document.getElementById("MyID").className
    .replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');

#3


52  

Here's a way to bake this functionality right into all DOM elements:

这里有一种方法,可以将此功能整合到所有DOM元素中:

HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName;
}

#4


38  

function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }

#5


30  

div.classList.add("foo");
div.classList.remove("foo");

More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList

更在https://developer.mozilla.org/en-US/docs/Web/API/element.classList

#6


24  

Edit

编辑

Okay, complete re-write. It's been a while, I've learned a bit and the comments have helped.

好的,完全的重写。已经有一段时间了,我学到了一些东西,这些评论对我很有帮助。

Node.prototype.hasClass = function (className) {
    if (this.classList) {
        return this.classList.contains(className);
    } else {
        return (-1 < this.className.indexOf(className));
    }
};

Node.prototype.addClass = function (className) {
    if (this.classList) {
        this.classList.add(className);
    } else if (!this.hasClass(className)) {
        var classes = this.className.split(" ");
        classes.push(className);
        this.className = classes.join(" ");
    }
    return this;
};

Node.prototype.removeClass = function (className) {
    if (this.classList) {
        this.classList.remove(className);
    } else {
        var classes = this.className.split(" ");
        classes.splice(classes.indexOf(className), 1);
        this.className = classes.join(" ");
    }
    return this;
};


Old Post
I was just working with something like this. Here's a solution I came up with...

// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
    Object.defineProperty(String.prototype,'trim', {
        value: function() {
            return this.replace(/^\s+|\s+$/g,'');
        },
        writable:false,
        enumerable:false,
        configurable:false
    });
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
    value: function(c) {
        if(this.className.indexOf(c)<0) {
            this.className=this.className+=' '+c;
        }
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double 
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
    value: function(c) {
        this.className=this.className.replace(c,'').replace('  ',' ').trim();
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});

Now you can call myElement.removeClass('myClass')

现在你可以调用骨髓元素。removeclass(“myClass”)

or chain it: myElement.removeClass("oldClass").addClass("newClass");

或链:myElement.removeClass(oldClass).addClass(“终极”);

#7


15  

It's very simple, I think.

我认为这很简单。

document.getElementById("whatever").classList.remove("className");

#8


8  

try:

试一试:

function removeClassName(elem, name){
    var remClass = elem.className;
    var re = new RegExp('(^| )' + name + '( |$)');
    remClass = remClass.replace(re, '$1');
    remClass = remClass.replace(/ $/, '');
    elem.className = remClass;
}

#9


4  

var element = document.getElementById('example_id');
var remove_class = 'example_class';

element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');

#10


2  

All of these answers are way too complicated, try

所有这些答案都太复杂了,试试看

var string = "Hello, whats on your mind?";
var new_string = string.replace(', whats on your mind?', '');

The result would be a return of the string

结果将是字符串的返回。

Hello

Super easy. Credits go to jondavidjohn Remove portion of string in Javascript

超级简单。请将Javascript中的字符串部分删除到jondavidjohn

#11


1  

I use this JS snippet code :

我使用这个JS代码片段:

First of all, I reach all the classes then according to index of my target class, I set className = "".

首先,我到达所有的类,然后根据我的目标类的索引,设置className = ""。

Target = document.getElementsByClassName("yourClass")[1];
Target.className="";

#12


-3  

There is also $.toggleClass, $.addClass, and $.removeClass. For documentation, take a look at http://api.jquery.com/toggleClass/.

还有美元。toggleClass,美元。addClass,.removeClass美元。有关文档,请查看http://api.jquery.com/toggleClass/。

Take a look at this jsFiddle example to see it in action.

看看这个jsFiddle示例,就可以看到它的作用。

#13


-5  

document.getElementById("whatever").className += "classToKeep";

With the plus sign ('+') appending the class as opposed to overwriting any existing classes

使用加号('+')附加类,而不是覆盖任何现有类