Like .closest()
which allows traversing from the element itself up through its ancestors, I am looking for a method for traversing from the element itself down through its descendants (so unlike .find()
which only traverses through the descendants, excluding the element itself).
I had a look at the list of traversing methods and couldn't find what I was looking for.
Is there a method in jQuery which is like .closest()
but for traversing down?
Just use addBack(selector) method:
$(this).find('.myclass').addBack('.myclass').first();
addBack('.myclass')
will add element itself only if matching the selector
Here a plugin that will find the closest (including itself):
$.fn.findClosest = function(selector) {
return this.is(selector) ? this.filter(selector).first() : this.find(selector).first();
};
The you call it like that :
$('#level-2').findClosest('.foo');
Fiddle : http://jsfiddle.net/W3WCQ/12/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With