Rohit Taur Rohit Taur - 3 months ago 13
PHP Question

How to remove class of a tag child in javascript

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>




Answer

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 = "";
    }
  }

}
<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>

Comments