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>

1

1 Answer 1

4

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.