清除div的文本,但使用jquery保留子节点

时间:2012-10-19 03:38:04

标签: javascript jquery html dom

  

可能重复:
  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>

在上面的示例中,我只想清除父"text of parent"div)的文本parent,保留子节点(child 1child2)完整。我怎么能用jQuery做到这一点?

4 个答案:

答案 0 :(得分:5)

尝试

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

http://jsfiddle.net/eUW47/1

答案 1 :(得分:3)

不要使用jQuery:

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

请参阅http://jsfiddle.net/Q8Bzv/

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

一般“删除所有子文本节点”功能(抱歉,没有jQuery):

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