stackoverflow002
stackoverflow002

Reputation: 329

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.

Upvotes: 2

Views: 2917

Answers (3)

RobG
RobG

Reputation: 147363

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.

Upvotes: 0

David G
David G

Reputation: 96790

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

});

Upvotes: 6

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Set the className property:

div.className = '';

Upvotes: 1

Related Questions