簡體   English   中英

如何從 div 內的所有元素中刪除特定屬性?

[英]How to remove specific attribute from all elements inside div?

如何從<div class="parent">內的所有元素(子元素)中刪除style屬性?

 function myFunction() { var divsname = Array.prototype.slice.call(document.getElementsByClassName("parent")); divsname.forEach(function(div) { divs.removeAttribute("style"); }); }
 <div id="container"> <div class="parent" name="parentone"> <div id="childone" style="height:10px"> <div id="childtwo" style="background-color:red"></div> </div> </div> <div class="parent" name="parenttwo"> <div id="childthree" style="height:10px"></div> </div> </div> <button onclick="myFunction()">Try it</button> <p id="demo"></p>

Select 的后代.parent ,而不是parent的元素。 目前尚不清楚您是否只想要孩子或所有后代 根據您的目的使用正確的組合器。

document.querySelectorAll(".parent *") // descendants
document.querySelectorAll(".parent > *") // children

然后,您可以將*替換為[style]到 select 僅實際具有style屬性的元素。

代替Array.prototype.slice.call ,使用更現代的Array.from

最后,只需使用forEach (和箭頭 function )刪除屬性。

Array.from(document.querySelectorAll(".parent [style]"))
  .forEach((elem) => elem.removeAttribute("style"));

暫無
暫無

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

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