Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

text

tags

If I have html like this:

<li id="listItem">     This is some text     <span id="firstSpan">First span text</span>     <span id="secondSpan">Second span text</span> </li> 

I'm trying to use .text() to retrieve just the string "This is some text", but if I were to say $('#list-item').text(), I get "This is some textFirst span textSecond span text".

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?

The HTML was not written by me, so this is what I have to work with. I know that it would be simple to just wrap the text in tags when writing the html, but again, the html is pre-written.

like image 473
MegaMatt Avatar asked Aug 09 '10 17:08

MegaMatt


People also ask

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 .

How do I get text within an element?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.

How do I get inner text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.


1 Answers

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(); 
like image 96
DotNetWala Avatar answered Oct 18 '22 01:10

DotNetWala