jQuery "hasParent"
For a clean re-usable solution, consider extending the jQuery.fn
object with a custom method used for determining the presence of a particular ancestor for any given element:
// Extend jQuery.fn with our new methodjQuery.extend( jQuery.fn, { // Name of our method & one argument (the parent selector) within: function( pSelector ) { // Returns a subset of items using jQuery.filter return this.filter(function(){ // Return truthy/falsey based on presence in parent return $(this).closest( pSelector ).length; }); }});
This results in a new method, $.fn.within
, that we can use to filter our results:
$("li").within(".x").css("background", "red");
This selects all list items on the document, and then filters to only those that have .x
as an ancestor. Because this uses jQuery internally, you could pass in a more complicated selector:
$("li").within(".x, .y").css("background", "red");
This will filter the collection to items that descend from either .x
or .y
, or both.
If I understand your question correctly, this would do:
$.fn.hasAncestor = function(a) { return this.filter(function() { return !!$(this).closest(a).length; });};$('.element').hasAncestor('.container').myAction();<div class="container"> <span> <strong class="element">strong</strong> </span></div>