Help understanding JQuery Attribute Equals Selecto

2019-06-25 05:14发布

问题:

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]')

回答1:

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.



回答2:

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.



回答3:

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".