igodie igodie - 4 months ago 34
HTML Question

How to delete specified children?


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


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--){

See this code working in this jsfiddle