4

For example we have the next code (it could 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 retrieve 'Take me' by jQuery selectors ?
NOTE: $('#test').text() will return all texts: Hello JS ...

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
Oleg Dats
  • 3,933
  • 9
  • 38
  • 61
  • 1
    This should help: http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery – Marc B Feb 08 '12 at 12:36
  • You can't, easily, with the HTML as specified. The best thing to do would be to wrap "Take me" in tags (span, for example), and select that. Failing that, you could get ALL the text, as you said, then extract the text between the noindex and div tags. That's really not a good idea though. – Ben Parsons Feb 08 '12 at 12:38

1 Answers1

4

Use contents() to get all the child nodes, then filter through looking for text nodes which match your criteria of containing "Hello".

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

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
  • it just doesn't make much sense to explicitly filter for a text which you already know. OP needs to make clear a "selector criteria". – jAndy Feb 08 '12 at 12:39
  • @jAndy It doesn't seem that odd to me. Maybe the OP wants to change that text node. – alex Feb 08 '12 at 12:41
  • no downvoting here. Well you might be right, however should be way more elegant for the OP to put those TextNodes into queryable elements. – jAndy Feb 08 '12 at 12:44
  • @jAndy Agreed, but sometimes the HTML is not easily modified (outputted from an archaic CMS like my current predicament). – alex Feb 08 '12 at 12:46