tags:

views:

123

answers:

2

Is there a way to get the deepest element matching a contains statement?

Basicly if I have nested divs, I want the last element not the parent element:

<div id="hayStack">
  <div id="needle">Needle</div>
</div>

$("div:contains('Needle')") is returning the hayStack div.

The only solution I have come up with so far is explicitly exlcuding parent divs by their id with .not

+2  A: 
$("div:contains('Needle')").filter(function() {
    return $(this).children().size() === 0;
});

Gets the list of elements containing 'Needle' then filters out those with any children.

Garry Shutler
Why would that be helpful? It may well have children, it should just not have any that contain "needle".
Tomalak
This will fail if the last div contains any HTML tags like "<br>" or even an <img>
duckyflip
+3  A: 

Adding :last will return the deepest/last div (the one immedietly encapsulating the content you are searching for

$("div:contains('Needle'):last")
duckyflip
I think it would return the last, not the necessarily the deepest.
Tomalak
Tomalak, since the jQuery engine fallows DOM structure and returns them in the order they are parsed inside the DOM Tree, if the needle has only 1 occurrence on the page, the last element will be the one closest to the needle (deepest inside the DOM Tree)
duckyflip
This is actually elegant and correct, the :contains selector returns a jQuery array and :last filters out the last one of them, being the closest parent.
David
Good to know. :-)
Tomalak
+1 for a great answer... but note this only works if you are looking for a single `Needle`
fudgey