Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery remove the innertext but preserve the html

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.

like image 806
Okky Avatar asked Jul 25 '13 07:07

Okky


3 Answers

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();
like image 143
adeneo Avatar answered Oct 26 '22 23:10

adeneo


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

like image 31
MaVRoSCy Avatar answered Oct 27 '22 00:10

MaVRoSCy


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/

like image 25
RobH Avatar answered Oct 27 '22 01:10

RobH