Richard
Richard

Reputation: 8280

Adding a predicate to jQuery's .first() method

Is it possible, without greatly impacting on the original source code, to extend the jQuery .first() method so that it can accept a predicate parameter? Fundamentally what I want it to do is something similar to LINQ's .First(), C# method. In JavaScript it would look something like this:

function first(arr, predicate) {
    for (var i = 0; i < arr.length; i++) {
        // return the first item fulfilling the predicate
        if (predicate.call(arr[i])) {
            return arr[i];
        }
    }
}

var myArray = [1, 3, 5],
    myPredicate = function() {
        return this >= 2;
    };

var result = first(myArray, myPredicate); // should give '3'

I know it can easily be achieved with JavaScript; I'm just curious if it's possible to easily extend an existing method within jQuery.

Solution used:

$.fn.firstOne = function(predicate) {
    // validate the predicate is a function
    if ($.isFunction(predicate)) {
        // iterate through each item, finding the first match
        for (var i = 0; i < this.length; i++) {
            if (predicate.call(this.eq(i), i)) {
                return this.eq(i);
            }
        }
    }

    // maintain chainability
    return $();
};

Upvotes: 2

Views: 1153

Answers (2)

Kevin B
Kevin B

Reputation: 95057

You can easily (and safely) create your own methods as needed,

$.fn.firstfn = function(fn) {
    return this.filter(fn).first()
}

$("#nav > li").firstfn(function() {
    return $(this).text() === "John Smith";
});

However I don't suggest you override existing methods. Just add your own methods.

Upvotes: 3

Chris
Chris

Reputation: 27394

You can easily extend jQuery with your own functions, see this question for how to do this

But it already has built in selectors to do first() with predicates / selectors. Here are some examples

$("#mycontainer li.classYouWant").first();
$("#mycontainer").find("another selector").first();
$("#mycontainer li a:first");

Upvotes: 1

Related Questions