Removing a class from Div in 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'm trying to do on every page used as an href in a div is to remove the class attribute from the li element that has it as active, and assign it to one, click.
I tried removeClass removeAttribute etc. but nothing works for me. I want to use simple javascript no jQuery
For example, my JS code on the game page removes the active class from the MyText page and adds it to the game page element.
I assume that 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 the following:
// Assuming `this` is your element this.classList.add("active"); Both of them will work in modern browsers. For older browsers, use the same DOM selection, then perform typical manipulations with the .className string.
active.className = active.className.replace(/\bactive\b/, " "); this.className += " active"; Try the function to remove the class:
function removeClass (parentEl, classToBeRemoved) { // DOM element, className for remove. var classes = parentEl.className.split(" "); for (var i = 0; i < classes.length; i++) { if (classes[i] == classToBeRemoved) { // Remove class. classes.splice(i, 1); } break; } parentEl.className = classes.join(" "); } Like this
.bold { font-weight: bold } .red { background: red } <div id="theDiv" class="bold red">Bold and red</div> <button id="button">Remove red</button> var theDiv = document.getElementById("theDiv"); var button = document.getElementById("button"); function removeRed() { var classContent = theDiv.className; theDiv.className = classContent.replace("red", "").trim(); } button.addEventListener("click", removeRed, false); on jsfiddle
In new browsers you can use element.classList and remove method