Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

dom - How to remove the class in javascript?

<div id="tab1" class="nav left">
<ul>
<li><a href="/magento/" class="now">Home</a></li>
......
</ul>
</div>

Now, i want to remove the class="now" or set the class value empty. If the url not on mangento, I using the following code. But the I don't know how to write the last part.

window.onload = function removeNow() {
    var div = document.getElementById("tab1").getElementsByTagName("a");
    if (window.location.pathname != '/magento/') {
        div.removeClass();
    }
}

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...