drake035
drake035

Reputation: 2877

How to do something different with first element in each loop?

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

Answers (4)

void
void

Reputation: 36703

$('.selector').each(function(i, el){
    if ( i === 0) {
       // Will be done to first element.
    }

});

Upvotes: 12

Josh Crozier
Josh Crozier

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

Gary Storey
Gary Storey

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

Oleksandr T.
Oleksandr T.

Reputation: 77482

As variant, like this

$( '.selector').each(function(index, element) {
   if (index === 0) {
      // if first element found, do something
   }
});

Or use

$( '.selector:first')

Example

Upvotes: 4

Related Questions