Hassan Raza
Hassan Raza

Reputation: 679

Unwrap all paragraph tags inside the div jquery

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.

Upvotes: 6

Views: 3041

Answers (5)

Madalina Taina
Madalina Taina

Reputation: 1978

You can use Javascript (is faster than Jquery because it uses native code):

http://jsfiddle.net/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.

Upvotes: 1

ro͢binmckenzie
ro͢binmckenzie

Reputation: 325

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.net/2wyrou4t/

Upvotes: 0

Developer
Developer

Reputation: 113

Simply use below code :-

$('p').contents().unwrap();

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

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.com/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>

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You 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

Upvotes: 3

Related Questions