Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between E>F and E+F selectors?

I read in jQuery that:

E>F matches all elements with tag name F that are direct children of E.

E+F matches all elements with tag name F that are immediately preceded by a sibling of tag name E.

What is the difference between both? Can one provide a clear and concrete example?

like image 894
Jérôme Verstrynge Avatar asked Dec 15 '22 21:12

Jérôme Verstrynge


1 Answers

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>
like image 105
BoltClock Avatar answered Dec 27 '22 12:12

BoltClock