tags:

views:

44

answers:

4

I have a set of span elements as below

<div>
  <span class='foo'>foo0</span>
  <span class='foo'>foo1</span>  
  <span class='foo'>foo2</span>
  <span class='foo'>foo3</span>
  <span class='foo'>foo4</span>
</div>

I have attached mouse in and mouse out events to each of the span elements. Now, on mouse in event is it possible to find out using jQuery whether the current hovered span element is the first span element with the class foo?

+2  A: 

Like this:

if($(this).is(':first-child'))
SLaks
but you don't check wheter the class is "foo" or not
GôTô
@GôTô: That goes in the main selector :) (in whose function you're using `this`).
BalusC
@BalusC: oh you mean the .is(':first-child') part checks for childs with same class as the one in the main selector?
GôTô
@GôTô: Have a look at jAndy's answer. You see that `this` is implicitly already `.foo`.
BalusC
@BalusC: Ah ok, so here SLaks assumes that the element is attached on .foo (from the reading of the question I assumed it was on span, but attaching on .foo makes more sense). Thanks for the explanation!
GôTô
+4  A: 

You might want to check it's .index()

$('.foo').bind('mouseover', function(){
    alert('I am ' + $(this).index());
});

If you explicitly need to only check for the first-child, use the selector :first-child.

$('.foo').bind('mouseover', function(){
    if($(this).is(':first-child'))
       alert('I am first');
});

Try it here: http://www.jsfiddle.net/YjC6y/5/

Reference.: .index(), .is(), :first-child

jAndy
A: 

Like so:

if($(this).is(":first-child")){
}
jvenema
A: 

All the answers provided here are correct. However, for a more general rule, you can use the :eq() selector:

$('.foo').bind('mouseover', function(){
    if($(this).is(':eq(0)')) {
       alert('I am first');
    }
});

(adapting jAndy's answer)

This tests that the element is at the 0th index among its siblings (i.e. is first -- eq uses zero-based indexing). You could check for the third item with

if ($(this).is(':eq(2)')) {
lonesomeday