How to remove the class in javascript?

前端 未结 3 516
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 02:50
<
相关标签:
3条回答
  • 2020-12-12 03:10

    In modern browsers you can use the classList API:

    div.classList.remove( 'now' );
    

    But a problem specific to your code: You must loop in order to remove the class. So try this:

    for ( var i = 0; i < div.length; i++ ) {
    
        div[i].classList.remove( 'now' );
    
    }
    

    If your browser doesn't support classList, use this removeClass shim:

    function removeClass( elem, name ) {
    
        var classlist = elem.className.split( /\s/ ), 
            newlist = [], 
            idx = 0;
    
        for ( ; idx < classlist.length; idx++ ) {
            if ( classlist[ idx ] !== name ) {
                newlist.push( classlist[ idx ] );
            }
        }
    
        elem.className = newlist.join(" ");
    
        return true;
    }
    

    or with jQuery (with which we are not required to use classList or className):

    $('a').each(function() {
    
        if (window.location.pathname != '/magento/')
            $(this).removeClass();
    
    });
    
    0 讨论(0)
  • 2020-12-12 03:20

    Set the className property:

    div.className = '';
    
    0 讨论(0)
  • 2020-12-12 03:23

    Note that getElementsByTagName returns a (possibly empty) NodeList, so:

    var div = document.getElementById("tab1").getElementsByTagName("a");
    

    is a collection of all the A element descendents of the element with ID "tab1" (and so 'div' is probably not a good name).

    If all you want to do is remove all class values of the first such A element, then:

    div[0].className = '';
    

    will do the job. But since the NodeList might be empty, the following would be more robust:

    if (div[0]) {
        div[0].className = '';
    }
    

    or perhaps

    div[0] && div[0].className = '';
    

    it depends on your coding style and maintainability requirements.

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