jQuery $.fn.within

Filter elements based on existence of an ancestor.

by Jonathan Sampson

HTML

<ul class="x"><li>1</li><li>2</li><li>3</li></ul>
<ul class="y"><li>4</li><li>5</li><li>6</li></ul>

JavaScript

// Extend jQuery.fn with our new method
jQuery.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).parents( pSelector ).length;
        });
    }
});

// Of all list items, modify those found within .x
$("li").within(".x").css("background", "red");