I’m looking for a way to select elements that contain a certain element and then filter the results to get only the highest level. Difficult to explain but made easier with an example:
<div id="one">
<div id="two">
<div id="three" class="find-me"></div>
</div>
</div>
<div id="four">
<div id="five" class="find-me"></div>
</div>
In this case, I would want my set to contain #one and #four. If I try to do something like this:
var elements = $('div').has('.find-me');
I get elements #one, #two and #four.
Note: By ‘highest level’ relates to the topmost element in the first selector, $('div') in this case.
Well the definition of what the
highest levelis, is a bit ambiguous because in practice if there is any.find-mein your page the highest level parent would behtmltag! which is useless.By defining your problem more specifically you can come up with a clearer definition for this
highest-definitionand for example saythe farthest div parentet. and in order to traverse parents of an element you can use.parents()and.closest()methods.obviously if you have more than one occurances of
find-meyou need to run this in a.each()loop.see an example here: http://jsfiddle.net/GsQDb/3/