30

can I remove with jQuery only the text in a node but not the children elements ?

thanks

aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • See also:[How do I select text nodes with jQuery](https://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery) – freedomn-m Oct 21 '22 at 14:12

6 Answers6

64

Best and easy solution to remove all text elements from certain div is

$("#firstDiv").contents().filter(function(){
    return (this.nodeType == 3);
}).remove();
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60
8

This works for me:

$(elem).html($(elem).html().replace($(elem).text(),''));

This set the html content without the text content, it means that any html tag inside of elem will be keep without changes.

before:

<div>Hello<input type="text" name="username" value="world!"/></div>

after:

<div><input type="text" name="username" value="world!"/></div>

bye

Nan1488
  • 179
  • 2
  • 6
  • 2
    Please add some explanation. – Paul R Nov 21 '12 at 22:20
  • 2
    There are a few problems with this: 1) editing HTML with string functions like replace can break the markup (eg. if the text is ' ' or '"'), 2) anything matching the text is replaced (eg. if the text is 'user' then the name attribute will change), 3) If the text is spread out between children it won't work (eg. "
    Hello
    World
    ")
    – Warbo Jun 20 '14 at 12:51
7

Here's my idea:

function removeText(element){
  var newElement = $('<' + element[0].nodeName + '/>');
  for(i=0; i < item.attributes.length; i++) {
    newElement.attr(item.attributes[i].name, item.attributes[i].value);
  } 
  element.children().each(function(){
    newElement.append(this);
  });
  element.replaceWith(newElement);
}
Rudism
  • 1,585
  • 10
  • 13
-1

It's easier for me to set a class for them all, in HTML and use empty() method in jQuery.

-6

you cannot do that.Unless it is wrapped by an element.

ozsenegal
  • 4,055
  • 12
  • 49
  • 64
-11
$('#someElement').text('');
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928