问题
I read in jQuery that:
E>F
matches all elements with tag nameF
that are direct children ofE
.
E+F
matches all elements with tag nameF
that are immediately preceded by a sibling of tag nameE
.
What is the difference between both? Can one provide a clear and concrete example?
回答1:
First off, as jQuery borrows both >
and +
from CSS, they behave the same way as described in the Selectors spec; see child combinator and adjacent sibling combinator.
"Children" refer to elements nested one level within another element. To emphasize the restriction of immediate nesting these may be referred to as "immediate children", as in the documentation, but they mean the same. Elements contained in any nesting depth are known as "descendants"; this includes children, grandchildren, great grandchildren and so on.
The selector E>F will only match the F
element in the following structure:
<E>
<F></F>
</E>
But not in the following structure (which would be matched by E F, D>F
or even E>D>F
instead):
<E>
<D>
<F></F>
</D>
</E>
A more real-world illustration can be found in this answer. As mentioned, although it covers CSS, it's the same since jQuery borrows it from CSS anyway.
"Siblings" refer to elements on the same nesting level; i.e. elements that are children of the same parent element. There can be next/following siblings and previous/preceding siblings as long as they all share the same parent, but in this case, "F
elements that are immediately preceded by E
elements" refers to F
elements that come immediately after E
elements, with no other sibling elements between them.
The selector E+F will only match the F
element in the following structure:
<E></E>
<F></F>
But not in the following structure (which would be matched by E~F, D+F
or even E+D+F
instead):
<E></E>
<D></D>
<F></F>
A more real-world illustration can be found in this answer.
Finally, here's a more complex scenario with a variety of elements, showing which F
elements are matched by which of the above selectors for comparison:
<root>
<D>
<F></F> <!-- Not matched -->
</D>
<E>
<E>
<F></F> <!-- E>F only -->
</E>
<F></F> <!-- E>F, E+F -->
</E>
<F></F> <!-- E+F only -->
</root>
回答2:
E > F = parent > selected
<parent>
<selected />
</parent>
E + F = preceding_sibling + selected
<parent>
<preceding_sibling />
<selected />
</parent>
回答3:
The following DOM structure should explain the difference between sibling and child to you:
-- Element
-- Sibling
-- Sibling
-- Child
-- Another Child
-- Sibling
回答4:
$('E>F').css({fontWeight:'bold'});
= F immediate children of E
<E>
<F>Bold text</F>
<A><F></F></A> // here 'F' is not immediate children of E
</E>
$('E+F').css({fontWeight:'bold'});
= F like next sibling of E
<E></E>
<F>Bold text</F>
<A></A>
<F></F> // here 'F' is not preceded by E
PLAYGROUND
来源:https://stackoverflow.com/questions/11493561/difference-between-ef-and-ef-selectors