最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unwrap all paragraph tags inside the div jquery - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 3

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

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/

发布评论

评论列表(0)

  1. 暂无评论