-1

<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

igodie
  • 497
  • 1
  • 4
  • 16
  • Possible duplicate of [Remove element by id](http://stackoverflow.com/questions/3387427/remove-element-by-id) – Madhawa Priyashantha Nov 20 '16 at 01:20
  • 1
    Thanks for this question. I was just out to dinner with my teenage son and wondering the same thing. :) – Paul Nov 20 '16 at 01:33
  • 1
    What kind of a father would delete his children?! And without even naming them... That's so sad – Myst Nov 20 '16 at 01:34
  • It's actually more accurately a duplicate of [**remove element by tag name**](http://stackoverflow.com/q/14003606/2902660) – Pineda Nov 20 '16 at 01:37

3 Answers3

3

You can use a CSS selector.

You can do it using jQuery or VanillaJS. For instance, here is my code for VanillaJS.

var headers = document.querySelectorAll('h1');
headers.forEach(function(h) { h.remove(); });

This will effectively remove the headers from the DOM.

gretro
  • 1,934
  • 15
  • 25
  • Yes, assuming you are in an environment in which `forEach` is defined on the result of `querySelectorAll`. –  Nov 20 '16 at 03:02
  • In the case you don't have access to it, you can use jQuery (for example) to do that for you or you can use a polyfill. – gretro Nov 20 '16 at 04:44
1

We can create our own fn to remove node by tag for usability. please review this one:

function rem(tag) {
  var h = document.querySelectorAll(tag); //return NodeList not array    
  [].forEach.call(h,function(elm) {            
      elm.parentNode.removeChild(elm);
  });
}

//passing tag to remove
rem('p');
<body>
  <p>dfg</p>
  <h1>yoyo</h1>
  <h1>yoyo2</h1>
  <ul>
    <li>somo</li>
  </ul>
</body>
RizkiDPrast
  • 1,695
  • 1
  • 14
  • 21
  • 1
    Why is the `if (h.parentNode` check necessary? And are you sure `forEach` will work on the result from `querySelectorAll`? –  Nov 20 '16 at 03:04
  • Thanks @torazaburo, I tried to so many times to get `if(h.parentNode)` return `false` but failed. I just edited my answer including fixing how we should handle NodeList return by `querySelectorAll` – RizkiDPrast Nov 20 '16 at 04:29
0

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.

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

Pineda
  • 7,435
  • 3
  • 30
  • 45
  • 1
    It would be simpler to just say `while (h1Elems.length) h1Elems[0].remove();`. –  Nov 20 '16 at 03:05