0

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>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
maja
  • 177
  • 1
  • 13
  • Inline event handlers like `onclick` are [not recommended](https://stackoverflow.com/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](https://stackoverflow.com/a/43459991/4642212) way of registering events. Always [use `addEventListener`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_—_dont_use_these) instead. – Sebastian Simon Nov 11 '19 at 09:56

1 Answers1

3

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"));
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75