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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With