Expand all paragraph tags inside a jquery div

Here I have a html sample where I want to expand all the paragraph tags inside a 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 it like that.

 <div class="divclass"> Hi this is some text. testing test <a href="#" rel="nofollow">Testing text2</a> </div> 

Thanks in advance.

+5
source share
5 answers

You need to expand the contents of p elements:

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

However, you have an element p that has no content. such tags will not be deleted with the code. you need to find p siblings and then delete it .:

 $('div p').contents().unwrap().siblings('p').remove(); 

Working demo

+1
source

You can use Javascript (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, and then uses .contents () to target the content of <p> , and then .unwrap() to remove its parent element <p> .

+1
source

Try it,

 // 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> 
0
source

Just use the code below: -

$ ('p') content () expand (); ..

0
source

It is more efficient to use replaceWith (), which is less expensive than unpacking ().

It also works for empty tags.

 $(".divclass p").replaceWith(function() { return $(this).contents(); }); 

JSFiddle: http://jsfiddle.net/2wyrou4t/

0
source

All Articles