Find enable yourself with jQuery (e.g. closest but intersect)

Like .closest() , which allows you to move from the element itself through its ancestors, I am looking for a method to move from the element itself down through its descendants (so unlike .find() , which passes only through the descendants, excluding the element itself) . I looked through the list of move methods and could not find what I was looking for.

Is there a method in jQuery that is similar to .closest() but for going down?

+4
source share
2 answers

Here is the plugin that will find the closest (including itself):

 $.fn.findClosest = function(selector) { return this.is(selector) ? this.filter(selector).first() : this.find(selector).first(); }; 

You call it this way:

 $('#level-2').findClosest('.foo'); 

Fiddle: http://jsfiddle.net/W3WCQ/12/

+4
source

Just use the addBack (selector) method :

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

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

+6
source

Source: https://habr.com/ru/post/1490370/


All Articles