2

Newb question:

jQuery('.foo')[0] does the job most of the time. jQuery('.foo:first')[0] is slightly more explicit and performant. But this isn't nice when array is empty, so check is necessary.

But is there a better way than to use array indexer? i.e. return is a single object or null if not found.

I know it's by design an array is always returned as jQuery's power lies in the "set" operations. But sometimes a more concise syntax does help readability and avoid bugs.

5
  • This came up a few days ago... Commented Sep 29, 2009 at 14:18
  • when the array is empty, [0] will return 'undefined' .. is it important that you get 'null' instead ?? Commented Sep 29, 2009 at 15:10
  • BTW undefined == null (altho undefined !== null) Commented Sep 29, 2009 at 15:11
  • It does save me a length check, but I'm trying to avoid putting [0] everywhere. Commented Sep 29, 2009 at 15:24
  • Oh, and doesn't [0] break closure as well since it's not a jQuery object necessarily? Commented Sep 29, 2009 at 15:29

3 Answers 3

3

I made you this plugin, hope it's useful:

//return single DOM element or null
jQuery.fn.getFirst = function() {
    var ele = jQuery(this).filter(':first')[0];
    if(ele !== undefined) {
        return ele;
    }
    return null;
};

Simple test case:

<input name="foo" value="hooohooo" class="test"/>
<input name="bar" value="heeeeheeee" class="test"/>

jQuery(document).ready(function() {    
    alert(jQuery('.test').getFirst()); //alerts [object HTMLInputElement]
    alert(jQuery('.nonExistent').getFirst()); //alerts 'null'
});

I don't know if getFirst is the best name for it, any suggestions? I've also thought single and first but can't seem to make up my mind.

Sign up to request clarification or add additional context in comments.

3 Comments

+1, nice. Perhaps 'firstResult'? (Though 'getFirst' seems plenty descriptive.)
I like this one. I think "first" is a fitting name. Single may imply that there should ONLY be single element in the result, as in .Net Single() extension method.
I'm surprised that jquery didn't have this as native API since it is so frequently used. It has so many other nice syntactical sugars that made javascript pleasant...
1

If I the selector is not guaranteed to return at least one element, I tend to iterate the collection with each().

jQuery('.foo').each(function() {
    this;
});

I even do this if I am qualifying the selector with something like :first.

jQuery('.foo:first').each(function() {
    this;
});

Edit: I see other answers implementing a "getFirst" method. Although I fail to see its usefulness, here is my take on it. It has the same functionality, but I think one is a more fitting name - avoiding confusion with the :first selector. I would be interested to see a use case for this.

/**
 * Return the first item of the collection, or
 * null if the collection is empty.
 */
jQuery.fn.one = function() {
    return this[0] || null;
};

Comments

0

You definitely need an extension for something like this:

$(document).ready(function () {
    jQuery.fn.getFirst = function () {
        if( this.length == 0 )
            return null;
        else
            return this.get(0);
        }

    var ret = 0;
    ret = $(".foo").getFirst();

    if( ret )
        $(ret).text( "Tight!" );

There you go, no more array subscripting!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.