views:

57

answers:

3

What is wrong with this jQuery selector?

$("#masterHeaderMenu.masterHeaderMenuButton a:first")

I'm intending to select the first anchor tag that is a child of an element whose class is "masterHeaderMenuButton", itself a child of the element with an "id" attribute value of "masterHeaderMenu".

Can't I do this in jQuery?

+6  A: 

You need an extra space in there, like this:

$("#masterHeaderMenu .masterHeaderMenuButton a:first")

Without the space, #masterHeaderMenu.masterHeaderMenuButton is looking for an element that has id="masterHeaderMeny" and class="masterHeaderMenuButton", with the space, it's saying find class="masterHeaderMenuButton" that's a descendant of the #masterHeaderMeny, not the same element.

If you want to go down any number of levels, add a space, if you want to go down only a level, use >, this means only go down to immediate children.

Nick Craver
+1 for mention of the Direct Decendent `>`
gnarf
+4  A: 

You can. You need a space between the first element (ID) and the second (class):

$("#masterHeaderMenu .masterHeaderMenuButton a:first")

Your selector looked for an element that had the ID "masterHeaderMenu" and CSS class "masterHeaderMenuButton".

Evgeny
A: 

There is no need of specifying class. if you give the ID name in the selector itself is enough. An ID can represent single html element in the document. but the class can represent a group of html elements.

$("#masterHeaderMenu .masterHeaderMenuButton a:first")

this selector may take time. the same result can be get from this code $("#masterHeaderMenu a:first")

This is incorrect, if he has 20 elements beneath `#masterHeaderMenu` with links your "same result" answer will get the first link from all of them, not the first link from the one with that class, they are **not** the same.
Nick Craver
I was wrong! I thought that he intending to select the first anchor tag which is a child of an element whose class is "masterHeaderMenuButton", and it has id "masterHeaderMenu".