2012-10-19 84 views
3

可能重複不斷子節點:
jQuery: how to remove the text but not the children elements格的清除文字,但使用jQuery

<div id="parent" style="border:2px solid red; width:300px;height:200px"> 
    text of parent 
    <div id="child1" style="border:1px solid green; width:200px;height:80px"></div> 
    <div id="child2" style="border:1px solid blue; width:200px;height:80px"></div> 
</div> 

在上面的例子,我想清楚了只有父母div的文本"text of parent"parent),保持子節點(child 1,child2)完好無損。我如何使用jQuery來做到這一點?

+0

複製? http://stackoverflow.com/questions/2715167/jquery-how-to-remove-the-text-but-not-the-children-elements – Sumo

+0

是的..重複..對不起,我發現他們才提問: ( – GirishK

回答

4

嘗試

$("#parent").contents().filter(function(){ 
    return (this.nodeType == 3); 
}).remove(); 

http://jsfiddle.net/eUW47/1

+1

我只是使用'.filter()':http://jsfiddle.net/yBkG8/2/ – Blender

+0

@Blender好主意。 – Musa

+0

你剛剛教會了我一些新的東西。從來沒有聽說過nodeType。太精彩了。 –

3

不要使用jQuery:

var div = document.getElementById("parent"); 
div.firstChild.data = "";​ 

http://jsfiddle.net/Q8Bzv/

+0

你是對的,它現在已經修復了。:) – jtfairbank

+0

是的......用普通的javascript來完成它的好方法。 – GirishK

0

試試這個:

var $children = $("#parent").children(); 
$("#parent").html("").append($children);​ 
0

一般的 「刪除所有子文本節點」 功能(對不起,沒有jQuery的):

function removeTextNodes(el) { 
    var nodes = el.childNodes, i = nodes.length; 
    while (i--) 
    if (nodes[i].nodeType == 3) el.removeChild(nodes[i]); 
}