简体   繁体   中英

How to remove specific attribute from all elements inside div?

How to remove style attributes from all elements (children) inside the <div class="parent"> ?

 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 the descendants of .parent , not the elements with the class parent . It's not quite clear whether you only want the children or all descendants . Use the right combinator for your purpose.

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

Then, you can replace * by [style] to select only elements that actually have a style attribute.

Instead of Array.prototype.slice.call , use the more modern Array.from .

Finally, just remove the attributes using forEach (and an arrow function ).

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

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