In jQuery you can call closest
to find the closest parent.
If I have a a
in a li
in a ul
in a td
in
Here is a simple implementation of the .closer()
method that returns the selector that is closest to the given element:
$.fn.closer = function(varargs) {
var $elem = $(this);
while ($elem.length) {
for (var i = 0, len = arguments.length; i < len; i++) {
if ($elem.is(arguments[i])) {
return arguments[i];
}
}
$elem = $elem.parent();
}
return null;
};
See it in action on jsFiddle.