Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find including itself with jQuery (like closest but traversing down)

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?

like image 691
Max Avatar asked Dec 21 '22 03:12

Max


2 Answers

Just use addBack(selector) method:

$(this).find('.myclass').addBack('.myclass').first();

addBack('.myclass') will add element itself only if matching the selector

like image 57
A. Wolff Avatar answered Jan 10 '23 23:01

A. Wolff


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/

like image 23
Karl-André Gagnon Avatar answered Jan 10 '23 22:01

Karl-André Gagnon