2

I need to select only the innermost div tag that contains specific text when the number of nested div tags is not known.

Given:

<div>
    <div>
        <div>Some Text</div>
    </div>
</div>

The selector should only contain the innermost div tag (and text). Using $("div:contains('Some Text')") returns all three divs since they all contain the text.

markm247
  • 97
  • 9
  • 1
    Maybe something like: `$('div:not(:has(div))');`? – Joe May 27 '14 at 21:07
  • 1
    Do you want to select the element by text or only by "level"? It's not clear from your description. – Felix Kling May 27 '14 at 21:09
  • @Joe - doesn't work since I need to specify the text. – markm247 May 27 '14 at 21:13
  • 3
    @markm247: Just add `:contains('Some Text')`. – Felix Kling May 27 '14 at 21:14
  • @FelixKling - I mentioned that I wanted to select div that contains text but I've edited the question for clarity. – markm247 May 27 '14 at 21:14
  • I'm inclined to close the question as duplicate of [jQuery selector for an element that directly contains text?](http://stackoverflow.com/q/7896455/218196), because that seems what you really want to do. – Felix Kling May 27 '14 at 21:16
  • @FelixKling - It is the same issue. Answer below is a better one than the question you mentioned. Not sure how that is handled on Stack Overflow. Thanks! – markm247 May 27 '14 at 21:28

1 Answers1

3

Use :contains() to find a div that contains your text, and then filter with :not(:has(div)):

$('div:contains(Some Text):not(:has(div))')

Demo:

http://jsfiddle.net/8eGLJ/1/

LGVentura
  • 1,547
  • 1
  • 11
  • 17