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?

Community
  • 1
  • 1
GirishK
  • 1,823
  • 3
  • 16
  • 23

4 Answers4

5

Try

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

http://jsfiddle.net/eUW47/1

Musa
  • 96,336
  • 17
  • 118
  • 137
3

Don't use jQuery:

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

See http://jsfiddle.net/Q8Bzv/

jtfairbank
  • 2,311
  • 2
  • 21
  • 33
0

Try this:

var $children = $("#parent").children();
$("#parent").html("").append($children);​
nix
  • 3,262
  • 2
  • 21
  • 36
0

A general "remove all child text nodes" function (sorry, no jQuery):

function removeTextNodes(el) {
  var nodes = el.childNodes, i = nodes.length;
  while (i--)
    if (nodes[i].nodeType == 3) el.removeChild(nodes[i]);
}
RobG
  • 142,382
  • 31
  • 172
  • 209