Last active
February 17, 2016 08:42
-
-
Save Alex1990/d5fb84c368486cc8bee0 to your computer and use it in GitHub Desktop.
An jQuery function to get the closest descendant element which matches the specified selector.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * closestDescendant | |
| * An jQuery function to get the closest descendant element which matches the specified selector. | |
| * The search strategy is breadth-first. | |
| */ | |
| ;(function () { | |
| $.fn.closestDescendant = function (selector) { | |
| var $elem = $(); | |
| this.each(function () { | |
| var matchedSet = $(this).find(selector).toArray(); | |
| var queue = $(this).children().toArray(); | |
| while (queue.length) { | |
| var $current = $(queue.shift()); | |
| if ($.inArray($current[0], matchedSet) > -1) { | |
| $elem = $elem.add($current); | |
| break; | |
| } | |
| queue = queue.concat($current.children().toArray()); | |
| } | |
| }); | |
| return $elem; | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment