views:

507

answers:

5
+1  Q: 

jQuery selector

Trying to select anchor tags that are a descendants of a div with a particular id, say it is #mydiv1, #mydiv2 and #mydiv3.

myFunction = function() {    
  var theDivs = $("#mydiv1, #mydiv2, #mydiv3");    
  theDivs.hover(function(e){    
      $(this+" a:link").css("color","#99ccff");
  },function(e){
      $(this+" a:link").css("color","#848484");        
  });    
}

The selector $(this+" a:link") doesn't seem to be selecting anything though.

Does anyone have any thoughts on the proper syntax for this selection?

+10  A: 

Try $(this).find("a:link").

EDIT: extra info

When you $(this + "query") you're mixing types. jQuery's selector param is looking for either a query string or an object. When 'this' gets converted to a string it isn't going to be valid selector syntax. For example, you could do something like this: $("." + this.className + "[query]").

Paul
+4  A: 

You can give an element for context, the following should work:

$("a:link", this).

It will search for the anchors starting in "this" node.

Miquel
Yeah, this is probably better. :)
Paul
Internally, providing context just calls find() after a chunk of case-checking code, meaning that calling find() directly is (very slightly) faster.
Ben Blank
But using the 'Write less, do more' philosophy, I would favor this over my first answer. I think using find makes it a bit clearer what is wrong with the OP though.
Paul
I not 100% sure but I think that if you do $(this).find(), jQuery need to build the wrapper arround this first and therefore you'll loose the speed gain of calling find() directly.
Miquel
A: 

Or try $(this).childred("a:link")

Chris Brandsma
A: 

Either of the above methods should work, but I don't see anything in the jQuery selector syntax about ":link" being valid syntax. Perhaps try leaving that off as well if the above methods don't work for you.

And the reason your original method didn't work is that "this" is a DOM element, not a string in your code. As previously mentioned, you can make it a jQuery object by doing "$(this)" or just use the DOM element as the search context.

kbosak
A: 

Iterate over the divs with .each(), and use the child selector:

  myFunction = function() {    
      var theDivs = $("#mydiv1, #mydiv2, #mydiv3");    
  theDivs.each(function(){    
      $(this > 'a').css("color","#99ccff");
  });    
}

Like so.

b. e. hollenbeck