Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 687
Hassan Raza Avatar asked Sep 10 '15 10:09

Hassan Raza


2 Answers

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

like image 142
Milind Anantwar Avatar answered Nov 08 '22 06:11

Milind Anantwar


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.

like image 38
Madalina Taina Avatar answered Nov 08 '22 06:11

Madalina Taina