3

Possible Duplicate:
jQuery: how to remove the text but not the children elements

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

In the above example, I want to clear only text "text of parent" of parent div (parent), keeping child nodes(child 1, child2) intact. How can I do this using jQuery?

4

4 回答 4

5

尝试

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

http://jsfiddle.net/eUW47/1

于 2012-10-19T03:43:12.923 回答
3

不要使用 jQuery:

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

http://jsfiddle.net/Q8Bzv/

于 2012-10-19T03:39:32.667 回答
0

一个通用的“删除所有子文本节点”功能(对不起,没有 jQuery):

function removeTextNodes(el) {
  var nodes = el.childNodes, i = nodes.length;
  while (i--)
    if (nodes[i].nodeType == 3) el.removeChild(nodes[i]);
}
于 2012-10-19T04:05:12.433 回答
0

尝试这个:

var $children = $("#parent").children();
$("#parent").html("").append($children);​
于 2012-10-19T03:42:39.847 回答