0

How do I remove class active. Below is my code, first I find id tag then class but this code is not working:

function myFunction() {
  var element1 = document.getElementById('grid3d');
  var remove_class = 'active';

  element1.className = element1.className.replace(' ' + remove_class, '').replace(remove_class, '');
}
.active {
  color: red;
}
<div id="grid3d">Hello World

  <figure ">Click the button to remove the class attribute from the h1 element.</figure>
    
    <figure class="active ">Click the button to remove the class attribute from the h1 element.</figure>
    
    <figure>Click the button to remove the class attribute from the h1 element.</figure>
    </div>
    <button onclick="myFunction() ">Try it</button>
Ivan
  • 34,531
  • 8
  • 55
  • 100
Rohit Taur
  • 28
  • 6

3 Answers3

3

Try this snippet

function myFunction() {
  var fig = document.querySelectorAll('figure');

  for (var i = 0; i < fig.length; i++) {
    if (fig[i].className == "active") {
      fig[i].className = "";
    }
  }

}
.active {
  color: purple;  
}
<div id="grid3d">Hello World

  <figure>Click the button to remove the class attribute from the h1 element.</figure>

  <figure class="active">Click the button to remove the class attribute from the h1 element.</figure>

  <figure>Click the button to remove the class attribute from the h1 element.</figure>
</div>
<button onclick="myFunction()">Try it</button>
Ivan
  • 34,531
  • 8
  • 55
  • 100
cheralathan
  • 572
  • 5
  • 14
1

you can try use classList.remove() function on figure element

function myFunction() {
  var element1 = document.getElementById('grid3d'),
      remove_class = 'active',
      figureEl = element1.querySelector('.' + remove_class);


  figureEl.className.remove(remove_class);
}

I hope it will works.

legendemil
  • 146
  • 4
0

If I understand correctly you would like to remove the id of the second <figure>. You can use the JS method removeAttribute(). It enables you to remove any attribute from a element tag.

var removeClass = function(selector) {
  var el = document.querySelector(selector);
  el.removeAttribute('id');
}
#active {
  color: red;
}
<div>Remove #active! from the second figure tag

  <figure>Click the button to remove the class attribute from the h1 element.</figure>

  <figure id="active">Click the button to remove the class attribute from the h1 element.</figure>

  <figure>Click the button to remove the class attribute from the h1 element.</figure>
</div>
<button onclick="removeClass('#active')">Try it</button>
Ivan
  • 34,531
  • 8
  • 55
  • 100
  • You have completely change my condition as I mention this is a plugin any other to fix this with my same code – Rohit Taur Aug 13 '16 at 10:25
  • You need to work a little instead of asking for code correction. Do you want to delete a specific element or all elements that have .active? – Ivan Aug 13 '16 at 10:26