2013-12-14 83 views
1

我正在解析網頁中的html內容。如何從jQuery段落中刪除不需要的元素

我需要這段轉換:

<p>Bryan Cranston was a guest on the third episode of <a href="/wiki/ALF%27s_Hit_Talk_Show" title="ALF's Hit Talk Show">ALF's Hit Talk Show</a>. 
Bryan Cranston is an American actor best known for his roles as Walter White in <i>Breaking Bad</i>, for which he won three consecutive Outstanding Lead Actor in a Drama Series Emmy Awards; and as Hal, the father in <i>Malcolm in the Middle</i>.</p> 

到這一點:

<p>Bryan Cranston was a guest on the third episode of ALF's Hit Talk Show. 
Bryan Cranston is an American actor best known for his roles as Walter White in <i>Breaking Bad</i>, for which he won three consecutive Outstanding Lead Actor in a Drama Series Emmy Awards; and as Hal, the father in <i>Malcolm in the Middle</i>.</p> 

正如你所看到的,我只是保持我的元素,並刪除所有其他元素。

我被卡住,這是我到目前爲止有:提前 http://jsfiddle.net/JyxL4/1/

謝謝!

回答

2

我不知道你爲什麼使用每一個,但我認爲是必要的,那麼你可以使用方法.unwrap()刪除鏈接標籤,但保持內部的HTML。
試試這個:

$('p').each(function(){ 
    $(this).find('a').contents().unwrap(); 
}); 

或更容易

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

DEMO

+0

'$('p a')。contents()。unwrap();'應該做 –

+0

確定,但是在示例中OP使用了每一個,我保留它,好吧,我添加了這個解決方案,感謝提示@ArunPJohny –

1
$('p *').not('i').contents().unwrap(); 

$('p *').not('i').each(function(){ 
    $(this).replaceWith(this.childNodes); 
}); 

JSFIDDLE