簡體   English   中英

如何在JavaScript中刪除標記子類

[英]How to remove class of a tag child in javascript

如何刪除活動的班級。 以下是我的代碼,首先找到id標簽,然后再找到class,但是此代碼無法正常工作:

 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> 

試試這個片段

 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> 

您可以嘗試在圖形元素上使用classList.remove()函數

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


  figureEl.className.remove(remove_class);
}

我希望它能起作用。

如果我理解正確,則想刪除第二個<figure>的ID。 您可以使用JS方法removeAttribute() 它使您可以從元素標記中刪除任何屬性。

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM