10
votes

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.

4
instead of .text(), can try .val('')?Happy coder
@Happycoder still its not working :(Okky
To point out the problem in your code - you are cloning the element (which will create a new independant element) at first and then you do the operations on the clone, which will not affect the original element.Mx.

4 Answers

7
votes

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();
2
votes

Check out this fiddle

Suppose you have this html

<parent>
  <child>i want to keep the child</child>
  Some text I want to remove
  <child>i want to keep the child</child>
  <child>i want to keep the child</child>
</parent>

Then you can remove the parent's inner text like this:

var child = $('parent').children('child');
$('parent').html(child);

Check this fiddle for a solution to your html

var child = $('#firstDiv').children('span');
$('#firstDiv').html(child);

PS: Be aware that any event handlers bounded on that div will be lost as you delete and then recreate the elements

2
votes

Why try to force jQuery to do it when it's simpler with vanilla JS:

var div = document.getElementById('firstDiv'),
    i,
    el;

for (i = 0; i< div.childNodes.length; i++) {
    el = div.childNodes[i];
    if (el.nodeType === 3) {
        div.removeChild(el);
    }
}

Fiddle here: http://jsfiddle.net/YPKGQ/

0
votes

Check this out, not sure if it does what you want exactly... Note: i only tested it in chrome

http://jsfiddle.net/LgyJ8/

cleartext($('#firstDiv'));

function cleartext(node) {

    var children = $(node).children();
    if(children.length > 0) {

        var newhtml = "";
        children.each(function() {

            cleartext($(this));

            newhtml += $('<div/>').append(this).html();

        });

        $(node).html(newhtml);

    }
}