簡體   English   中英

解開div jquery中的所有段落標記

[英]Unwrap all paragraph tags inside the div jquery

這里我有示例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>

但我想要這樣。

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

提前致謝。

你需要打開p元素的內容:

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

但是你有p元素沒有內容。 這些標簽不會被代碼刪除。 你需要找到兄弟姐妹p然后刪除它:

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

工作演示

您可以使用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 ] );
}

這將選擇所有段落,然后使用.contents()來定位<p>的內容,然后使用.unwrap()來刪除其父<p>元素。

試試這個,

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

只需使用以下代碼: -

$( 'P')的內容()解開()。;

使用replaceWith()更有效,它的成本低於unwrap()。

它也適用於空標簽。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM