Javascript – Jquery remove the innertext but preserve the html

domjavascriptjquery

I have something like this.

<div id="firstDiv">
    This is some text
    <span id="firstSpan">First span text</span>
    <span id="secondSpan">Second span text</span>
</div>

I want to remove 'This is some text' and need the html elements intact.

I tried using something like

$("#firstDiv")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text("");

But it didn't work.

Is there a way to get (and possibly remove, via something like .text("")) just the free text within a tag, and not the text within its child tags?

Thanks very much.

Best Answer

Filter out text nodes and remove them:

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

FIDDLE

To also filter on the text itself, you can do:

$('#firstDiv').contents().filter(function() {
    return this.nodeType === 3 && this.nodeValue.trim() === 'This is some text';
}).remove();

and to get the text :

var txt = [];

$('#firstDiv').contents().filter(function() {
    if ( this.nodeType === 3 ) txt.push(this.nodeValue);
    return this.nodeType === 3;
}).remove();