简体   繁体   中英

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> 

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> 

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM