2012-06-18 20 views
0
<div> 
     <span>ABC</span> 
     <ul> 
      <li>list</li> 
      <li>list</li> 
      <span>ABC</span> 
      <li>list</li> 
     <ul> 
     <span>ABC</span> 
    </div> 

這是myString變量,現在我想從該字符串中刪除span元素?所以myString的將是:如何刪除html字符串中的元素

<div> 
     <ul> 
      <li>list</li> 
      <li>list</li> 
      <li>list</li> 
     <ul> 
    </div> 

感謝 (刪除()只適用於頂級元素)

+2

刪除也適用其他地方,檢查http://api.jquery.com/remove/ –

回答

4

嘗試:

var str = '<div><span>ABC</span><ul><li>1</li><li>2</li></ul><span>ABC</span></div>'; 
var without_span = $(str).find('span').remove().end(); 

end()獲取更新的字符串(從技術上講,返回堆棧中的最後一個選擇,即查找之前)。

演示http://jsfiddle.net/t2uNr/

+0

不工作:(... – Snoob

+0

它的工作原理,但可以解釋爲什麼結束( )作品 – Snoob

+2

@Snoob'end'得到更新後的字符串(從技術上說,返回堆棧中的最後一個選擇,即在'find'之前)。下面是同樣解決方案的另一個例子:http://jsfiddle.net/yhrvN/。 – VisioN

1

可以使用SUBSTR函數執行搜索和手動刪除它

0

它的工作對我來說....

$('div').find('span').remove(); 
+0

不起作用,只用一個字符串測試,而不是你的文檔 – Snoob

0

你可以嘗試:

$('ul').find(span:first).remove(); 

我建議你在你的UI分配一些類元素無論如何。

+0

我想刪除所有span元素,不在乎它們在哪裏 – Snoob

+0

$(document).find(span).remove(); – shareef

+0

$('span')。each(function(){ $(this).remove(); } – Ingro

1

有點硬編碼,但將工作。

var str = '<div><span>ABC</span><ul><li><li><li></li></ul><span>ABC</span></div>'; 
stringToReplace='<span>ABC</span>'; /*Enter string to be replaced here*/ 
var index = str.indexOf(stringToReplace); 
     while(index != -1){ 
      str=str.replace(stringToReplace,''); 
      index = str.indexOf(stringToReplace); 
     } 
alert(str);​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

http://jsfiddle.net/dVtCx/