tags:

views:

129

answers:

3

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.

+1  A: 

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;
};
Alex Barrett
+3  A: 

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.

karim79
+1, nice. Perhaps 'firstResult'? (Though 'getFirst' seems plenty descriptive.)
Jeff Sternal
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.
Xerion
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...
Xerion
A: 

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!

zdawg