2015-09-10 7 views
5

ここでは、divの中のすべての段落タグをアンラップするサンプルhtmlがあります。現在の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要素の内容アンラップする必要があります:あなたは内容を持たないp要素を持っているしかし

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

を。そのようなタグはコードでは削除されません。あなたは兄弟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

正確に、私は自分の答えを更新しました。 –

+0

はいまだ1つの '

'はアンラップされていません。 –

0

は、単にコードの下に使用し、これを試してください: -

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

0

unwrap()よりも安価なreplaceWith()を使用する方が効率的です。

これは空のタグでも機能します。

$(".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>要素。

関連する問題