Reputation: 2877
Within an each() loop, is it possible to do something with the first element in particular, not the next ones? Something like this:
$( '.selector').each(function(){
// if first element found, do something
});
Upvotes: 9
Views: 21453
Reputation: 36703
$('.selector').each(function(i, el){
if ( i === 0) {
// Will be done to first element.
}
});
Upvotes: 12
Reputation: 240878
You could determine if it is the first element by checking the index.
$('.selector').each(function(i, el) {
if (i === 0) {
// first element.. use $(this)
}
});
Alternatively, you could also just access the first element outside of the loop using the .first()
method:
$('.selector').first();
The :first
selector would also work:
$('.selector:first');
Upvotes: 6
Reputation: 1814
Probably not as efficient as it could be but it's straightforward:
$( '.selector').each(function(index){
if (index === 0) {
// first element found, do something
}
});
Upvotes: 3
Reputation: 77482
As variant, like this
$( '.selector').each(function(index, element) {
if (index === 0) {
// if first element found, do something
}
});
Or use
$( '.selector:first')
Upvotes: 4