Reputation: 3281
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.
Upvotes: 2
Views: 661
Reputation: 16455
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;
};
Upvotes: 1
Reputation: 1137
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!
Upvotes: 0
Reputation: 342635
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.
Upvotes: 3