Here i have the sample html where i want to unwrap all paragraph tags inside the div.Currently html looks like this.
<div class="divclass">
Hi this is some text.
<p>testing test</p>
<p></p>
<p><a href="#" rel="nofollow">Testing text2</a></p>
</div>
but i want like this.
<div class="divclass">
Hi this is some text.
testing test
<a href="#" rel="nofollow">Testing text2</a>
</div>
Thanks in advance.
Here i have the sample html where i want to unwrap all paragraph tags inside the div.Currently html looks like this.
<div class="divclass">
Hi this is some text.
<p>testing test</p>
<p></p>
<p><a href="#" rel="nofollow">Testing text2</a></p>
</div>
but i want like this.
<div class="divclass">
Hi this is some text.
testing test
<a href="#" rel="nofollow">Testing text2</a>
</div>
Thanks in advance.
Share Improve this question asked Sep 10, 2015 at 10:13 Hassan RazaHassan Raza 6791 gold badge10 silver badges27 bronze badges 2- 1 stackoverflow./questions/17271884/jquery-unwrap-div-within-p – Madalina Taina Commented Sep 10, 2015 at 10:19
- This can help too api.jquery./unwrap – Madalina Taina Commented Sep 10, 2015 at 10:38
5 Answers
Reset to default 3You need to unwrap the contents of p elements:
$('div p').contents().unwrap();
However you have p element which do not have contents. such tags will not be removed with code. you need to find the siblings p and then remove it.:
$('div p').contents().unwrap().siblings('p').remove();
Working Demo
You can use Javascript (is faster than Jquery because it uses native code):
http://jsfiddle/ks60L4h9/3/
var p = document.getElementsByTagName('p');
while(p.length) {
var parent = p[ 0 ].parentNode;
while( p[ 0 ].firstChild ) {
parent.insertBefore( p[ 0 ].firstChild, p[ 0 ] );
}
parent.removeChild( p[ 0 ] );
}
This selects all paragraphs, then uses .contents() to target the content of <p>
, then .unwrap()
to remove its parent <p>
element.
Try this,
// unwrap p tags having content;
$('.divclass p').contents()// get content of all p tags
.unwrap() // unwrap p tags
.siblings('p:empty') // get all p siblings which are empty
.remove(); // and finaaly remove it
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divclass">
Hi this is some text.
<p>testing test</p>
<p></p>
<p><a href="#" rel="nofollow">Testing text2</a></p>
</div>
Simply use below code :-
$('p').contents().unwrap();
It's more efficient to use replaceWith(), which has less cost than unwrap().
It also works for empty tags.
$(".divclass p").replaceWith(function() { return $(this).contents(); });
JSFiddle: http://jsfiddle/2wyrou4t/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742415298a4439624.html
评论列表(0条)