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 ...

2
  • 1
    This should help: stackoverflow.com/questions/298750/… Commented Feb 8, 2012 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. Commented Feb 8, 2012 at 12:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 It doesn't seem that odd to me. Maybe the OP wants to change that text node.
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 Agreed, but sometimes the HTML is not easily modified (outputted from an archaic CMS like my current predicament).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.