What's the best way to return a single object instead of an array from jQuery?

New question:

jQuery ('. foo') [0] does most of the work. jQuery ('. foo: first') [0] is slightly more explicit and efficient. But it's not good when the array is empty, so a check is necessary.

But is there a better way than using an array indexer? that is, return is a single object, or null if not found.

I know that by design, an array is always returned, since the power of jQuery lies in the "set" operations. But sometimes, a more concise syntax helps readability and avoids errors.

+2


source to share


3 answers


I made this plugin for you, hope it's helpful:

//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 is the getFirst

best name for it, any suggestions? I also thought that single

and first

but can't seem to solve.

+3


source


If my selector doesn't guarantee that at least one element will be returned, I try to iterate over it using each()

.

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

      

I even do this if I qualify a selector with something like :first

.



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

      

Edit: I see other answers that implement the getFirst method. While I don't see its usefulness, here's my job. It has the same functionality, but I think it one

is a more appropriate name - avoiding the selector confusion :first

. 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;
};

      

+1


source


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, don't sign arrays anymore!

0


source







All Articles