views:

92

answers:

3

Is it possible to use a :selector with the following in jQuery?

$('.galler_attr').bind('click', function() {
   $(this:first-child).css('color', 'red'); 
      });
+1  A: 

No. You're trying to mix the function context with a string.

Use this as the context of the selector or call find() on $(this) to search within the DOM scope of the element. Either

$('.galler_attr').bind('click', function() {
   $(this).find(':first-child').css('color', 'red'); 
});

or this (which resolves to the above internally):

$('.galler_attr').bind('click', function() {
   $(':first-child', this).css('color', 'red'); 
});
Russ Cam
thx a lot, very helpful!!
hoerf
A: 

in that case, use .is()

$('.galler_attr').bind('click', function() {
   $(this).is(':first-child').css('color', 'red');
   // this would change the color to red if the clicked element is a first-child....
});

I wonder why not just bind it to the first-child directly?

$('.galler_attr:first-child').bind('click', function() {
   // this would bind click event to the first-child element...
   $(this).css('color', 'red');

});
Reigel
A: 

Yes, you can use it but not in such a way. You can put it as Russ says.

$('.galler_attr').bind('click', function() {
   $(this).find(':first-child').css('color', 'red'); 
});

You can get better help for such problems by going to www.visualjquery.com. It's pretty.

Muhit