2015-09-10 29 views
5

这里我有示例html,我想解开div中的所有段落标签。目前的html看起来像这样。打开div中的所有段落标签jquery

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

但我想要这样。

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

在此先感谢。

+1

http://stackoverflow.com/questions/17271884/jquery-unwrap-div-within-p –

+0

这也可以帮助https://api.jquery.com/unwrap/ –

回答

1

你需要解开p元素的内容:

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

但是你有p元素不具备的内容。这些标签不会被代码删除。你需要找到姐弟俩P,然后将其删除:

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

Working Demo

+0

这只适用于第一段标签里面div。 –

+0

@HassanRaza:检查小提琴。它解开所有p元素并删除空p元素 –

+1

好的答案。爱它:) –

0

试试这个,

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

'

'不会被解开,因为它没有内容 –

+0

正确和我更新了我的答案,plz chk它。 –

+0

是仍然一个'

'不是没有解决。 –

0

只需使用下面的代码: -

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

0

使用replaceWith()比使用unwrap()更节省成本。

它也适用于空标签。

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

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

1

您可以使用JavaScript(比jQuery的更快,因为它使用本地代码):

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 ]); 
} 

这将选择所有段落,然后使用。内容()以内容<p>为目标,然后.unwrap()删除其父母<p>个元素。