Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to remove the text but not the children elements

Tags:

jquery

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

thanks

like image 834
aneuryzm Avatar asked Apr 26 '10 16:04

aneuryzm


People also ask

Which jQuery method is used to remove the child elements from the selected element?

The jQuery empty() method removes the child elements of the selected element(s).

How do I get just the text from HTML in jQuery?

The best way is to . clone() your object, . remove() all of its . children() , then go back to the object using .

What is the opposite of remove in jQuery?

version added: 1.4. The . detach() method is the same as . remove() , except that . detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

What jQuery method is used to completely remove attributes from elements?

To remove all attributes of elements, we use removeAttributeNode() method.


3 Answers

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

$("#firstDiv").contents().filter(function(){     return (this.nodeType == 3); }).remove(); 
like image 52
Nitin Varpe Avatar answered Nov 03 '22 19:11

Nitin Varpe


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

like image 32
Nan1488 Avatar answered Nov 03 '22 19:11

Nan1488


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);
}
like image 37
Rudism Avatar answered Nov 03 '22 17:11

Rudism