[英]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. 这里我有示例html我想在div中解开所有段落标签。目前html看起来像这样。
<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. 提前致谢。
You need to unwrap the contents of p elements: 你需要打开p元素的内容:
$('div p').contents().unwrap();
However you have p element which do not have contents. 但是你有p元素没有内容。 such tags will not be removed with code.
这些标签不会被代码删除。 you need to find the siblings p and then remove it.:
你需要找到兄弟姐妹p然后删除它:
$('div p').contents().unwrap().siblings('p').remove();
You can use Javascript (is faster than Jquery because it uses native code): 您可以使用Javascript(比Jquery更快,因为它使用本机代码):
http://jsfiddle.net/ks60L4h9/3/ 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. 这将选择所有段落,然后使用.contents()来定位
<p>
的内容,然后使用.unwrap()
来删除其父<p>
元素。
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>
Simply use below code :- 只需使用以下代码: -
$('p').contents().unwrap(); $( 'P')的内容()解开()。;
It's more efficient to use replaceWith(), which has less cost than unwrap(). 使用replaceWith()更有效,它的成本低于unwrap()。
It also works for empty tags. 它也适用于空标签。
$(".divclass p").replaceWith(function() { return $(this).contents(); });
JSFiddle: http://jsfiddle.net/2wyrou4t/ JSFiddle: http : //jsfiddle.net/2wyrou4t/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.