igodie igodie - 15 days ago 5
HTML Question

How to delete specified children?



<body>
<p>dfg</p>
<h1>yoyo</h1>
<h1>yoyo2</h1>
<ul>
<li>somo</li>
</ul>
</body>





For example I want to delete only h1 from body. The other children should stay

Answer

You can use getElementsByTagName to get an HTMLCollection (not an array) of the h1 tags, which is live.

When an element is removed, the elements update their indexes accordingly which means that you have to remove each element from the last position to the first.

Pure Javascript solution:

var h1Elems = document.getElementsByTagName('h1');

for(var i = h1Elems.length - 1;  i >= 0;  i--){
  h1Elems[i].parentElement.removeChild(h1Elems[i]);
}

See this code working in this jsfiddle

Comments