How to remove class attribute from div?

前端 未结 8 886
感情败类
感情败类 2021-02-05 13:12

I am using JavaScript and I want to add/remove a Class attribute if a button is clicked. I am able to add the class, but I don\'t know how to remove it. how can I do that?

相关标签:
8条回答
  • 2021-02-05 13:18

    For cross-browser support:

    buttonCom.onclick = function() {
        box.className = ''; // IE
        box.removeAttribute('class'); // Others
    };
    
    0 讨论(0)
  • 2021-02-05 13:23

    In the future-ish, you can also consider Element.classList.

       var d = document.getElementsByTagName('div')[0];
       d.classList; // []
       d.classList.add('foo'); // undefined
       d.classList; // ["foo"]
       d.classList.remove('foo'); // undefined
       d.classList; // []
    

    I say future-ish b/c you have to consider this IE < 10.

    0 讨论(0)
  • 2021-02-05 13:26
    function hasClass(ele,cls) {
        return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
    }
    function addClass(ele,cls) {
        if (!this.hasClass(ele,cls)) ele.className += " "+cls;
    }
    function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }
    

    You can use RegExp in theses three functions to check class existance, add class, and remove class. Here is the source openjs

    0 讨论(0)
  • 2021-02-05 13:28

    The nicest way to set classes with Javascript is to use the className property:

    // to add
    box.className = 'move';
    // to remove
    box.className = '';
    
    0 讨论(0)
  • 2021-02-05 13:29

    Simple:

    box.removeAttribute('class'); 
    

    See https://developer.mozilla.org/en/DOM/element.removeAttribute

    0 讨论(0)
  • 2021-02-05 13:30

    You should consider jQuery, than you can just use this: $('.itemclass').removeClass('classname');

    0 讨论(0)
提交回复
热议问题