Removing an Element's Parent with the Unwrap Method in jQuery
You can do the opposite, not wrap the element, but unwrap it (that is, remove the parent) using the method unwrap
.
In the following example, we have paragraphs that are inside div
tags:
<div><p class="www">text</p></div>
<div><p class="www">text</p></div>
<div><p class="www">text</p></div>
<div><p>text</p></div>
Let's perform the unwrap operation unwrap
on paragraphs with class www
:
$('.www').unwrap();
HTML the code will look like this:
<p class="www">text</p>
<p class="www">text</p>
<p class="www">text</p>
<div><p>text</p></div>
You can also pass a selector as a string to the method, then it will work if the element's parent matches the specified selector:
$('i').unwrap('p');
Find the p
paragraphs wrapped in div
divs and remove those divs.
Find all span
tags wrapped in p
paragraphs and delete those paragraphs without touching the span
tags.