How can I select text from a jQuery element

For example, we have the following code (it can be any tag with nested tags and text):

<td id='test'> Hello <a href='foo.html'>JS</a> <noindex>Map</noindex> Take me <div>nice</div> Skip me </tr> 

How can I get ' Take me ' using jQuery selectors?
NOTE: $('#test').text() will return all texts: Hello JS ...

+4
source share
1 answer

Use contents() to get all the child nodes, then filter the search for text nodes that match your criteria containing "Hello" .

 $('#test').contents().filter(function() { return this.nodeType == 3 && $.trim(this.data) == 'Take me'; }) 

jsFiddle .

+4
source

Source: https://habr.com/ru/post/1395408/


All Articles