Remove CSS class from element with JavaScript (no jQuery)

This question already has an answer here:

  • Change an element's class with JavaScript 30 answers

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

    ELEMENT.classList.remove("CLASS_NAME");
    

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


    document.getElementById("MyID").className =
        document.getElementById("MyID").className.replace(/bMyClassb/,'');
    

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


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

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

    以下是将此功能正确烧入所有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;
    }
    
    链接地址: http://www.djcxy.com/p/25198.html

    上一篇: 在div中设置新课程

    下一篇: 使用JavaScript从元素中删除CSS类(无jQuery)