Could anyone help me on how I can remove div
tags without removing their content in JavaScript
?
This is my html from which I need to remove all div tags:
<div id="id1" class="someclass">
<p>some text
<label> Test content </label>
</p>
<div id="id2" style="overfolw:scroll">
<span>some text</span>
<div id="level3">
<label> Test content </label>
<a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
</div>
</div>
</div>
Expected output would be like shown below.
<p>some text
<label> Test content </label>
</p>
<span>some text</span>
<label> Test content </label>
<a href=https://twitter.com/realDonaldTrump/status/882186896285282304 target=_blank rel=noopener>creepiness</a>
JavaScript provides the functionality of clearing the content of div. There are two methods to perform this function, one by using innerHTML property and other by using firstChild property and removeChild() method.
The remove() method removes an element (or node) from the document.
Given an HTML document containing div elements and the task is to remove the existing HTML elements using jQuery. To remove elements and its content, jQuery provides two methods: remove(): It removes the selected element with its child elements. empty(): It removes the child element from the selected elements.
To remove the parent element without removing its children, call the replaceWith() method on the parent element passing it the child nodes as a parameter, e.g. parent. replaceWith(... parent. childNodes) .
1.Using pure java-script:-
var divs=document.getElementsByTagName('div');
var counter = divs.length-1;
for(i=counter;i>=0;i--){
divs[i].outerHTML = divs[i].innerHTML;
}
<div id="id1" class="someclass">
<p>some text
<label> Test content </label>
</p>
<div id="id2" style="overfolw:scroll">
<span>some text</span>
<div id="level3">
<label> Test content </label>
<a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
</div>
</div>
</div>
2.You can use jQuery unwrap() also:-
$(document).ready(function(){
$('div').contents().unwrap();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1" class="someclass">
<p>some text
<label> Test content </label>
</p>
<div id="id2" style="overfolw:scroll">
<span>some text</span>
<div id="level3">
<label> Test content </label>
<a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With