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.
The best way is to . clone() your object, . remove() all of its . children() , then go back to the object using .
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With