Jquery remove the innertext but preserve the html

dom, javascript, jquery

Solution

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

Problem

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.

Original source

Related problems