How to remove text (without removing inner elements) from a parent element using jquery

If you want to remove all child text nodes you can use .contents() and then .filter() to reduce the matched set to only text nodes:

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

Here’s a working example.

Note: This will preserve any existing event handlers on the child elements, which answers using .html() will not do (since the elements are removed from the DOM and added back in).

Note 2: Answers in some of the linked questions show similar code to that in my answer here, but they use the nodeType constants (e.g. return this.nodeType === Node.TEXT_NODE). This is bad practice since IE below version 9 does not implement the Node property. It’s safer to use the integers (which can be found in the DOM level 2 spec).

Leave a Comment