views:

43

answers:

3

I want to find a <td role="foo" class="one two three four"> within a <div id="myid">

These two selectors work:

$('#myid td[role=foo]')

$('#myid .two')

But this one doesn't, why?

$('#myid .two td[role=foo]')
+9  A: 

Because a space in a selector string is a descendant-selector.

You would need to do:

$('#myid td.two[role=foo]')

The way you had it, you were searching for <td role="foo"> elements that are a descendant of .two.

patrick dw
+1 - Or `$('#myid td[role=foo].two')` ;)
Nick Craver
@Nick - Is that way more efficient?
patrick dw
@patrick - not really, just showing the order doesn't matter :)
Nick Craver
@Nick - Ok, wasn't sure since I saw that @cletus had that version as well. Thought maybe the selector worked right-to-left, or something. Thanks. :o)
patrick dw
+2  A: 

Because your selector:

$('#myid .two td[role=foo]')

is looking for a td[role=foo] within an element of class .two within an element of id #myid.

You're using descendant selectors, rather than looking for td[role=foo].two which, I think, is what you want.

David Thomas
+2  A: 

You want:

$("#myid td[role=foo].two")...

This selector:

$('#myid .two td[role=foo]')

means: find the element with ID "myid". From it find all descendants with a class of "two". From those elements find all descendants <td> elements that have a role attribute with a value of "foo".

cletus