Using .text() to retrieve only text not nested in child tags

Simple answer:

$("#listItem").contents().filter(function(){ 
  return this.nodeType == 3; 
})[0].nodeValue = "The text you want to replace with" 

I liked this reusable implementation based on the clone() method found here to get only the text inside the parent element.

Code provided for easy reference:

$("#foo")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();

This seems like a case of overusing jquery to me. The following will grab the text ignoring the other nodes:

document.getElementById("listItem").childNodes[0];

You'll need to trim that but it gets you what you want in one, easy line.

EDIT

The above will get the text node. To get the actual text, use this:

document.getElementById("listItem").childNodes[0].nodeValue;

Tags:

Text

Jquery

Tags