<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
<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
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.
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>
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]);
}