Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing class from a Div in Javascript [duplicate]

Tags:

javascript

I have a div section

<div class="1">
        <div id="tab1"">
            <ul class="nav nav-tabs">                   
                <li class="active ans-tab"> <a href="{$cdn2}">MyText</a></li>
                <li class="topTab"><a href="{$cdn2}/Game/">Game</a></li>
                <li class="topTab"><a href="{$cdn2}/lb/">LB</a></li>
            </ul>
        </div>
       <div id="tab2">
        <ul class="nav nav-pills">
            <li class="active"> <a href="{$cdn2}">Top</a></li>
            <li><a href="{$cdn2}/categories/">Categories</a></li>
        </ul>
    </div>
</div>

What i am trying to do at each of the pages used as href in the div, is to remove class attribute from the li item which has it as active and assign it to the one, i click.

I have tried removeClass removeAttribute etc but nothing seems to be working for me. I want to use plain Javascript no jQuery

For e.g. my JS code on Game page removes active class from MyText page and add it to Game page's li element.

like image 669
CodeMonkey Avatar asked Apr 22 '13 18:04

CodeMonkey


People also ask

How do I remove a class from a div?

Use the classList. remove() method to remove a class from a div element, e.g. box. classList. remove('my-class') .

What is classList JavaScript?

JavaScript classList is a DOM property of JavaScript that allows for styling the CSS (Cascading Style Sheet) classes of an element. JavaScript classList is a read-only property that returns the names of the CSS classes.

How to remove class from div in jQuery?

jQuery removeClass() Method The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.


1 Answers

I assume only one is active at a time. To remove, you can do this:

var active = document.querySelector(".active");

active.classList.remove("active");

Then to add, do this:

// Assuming `this` is your element
this.classList.add("active");

Both of these will work in modern browsers. For older browsers, use the same DOM selection, then do typical string manipulation of the .className property.

active.className = active.className.replace(/\bactive\b/, " ");

this.className += " active";
like image 64
silly little me Avatar answered Sep 28 '22 05:09

silly little me