Difference between E> F and E + F selectors?

I read in jQuery that:

E>F matches all elements with the tag name F , which are direct children of E

E+F matches all elements with the tag name F immediately preceded by the tag name E

What is the difference between the two? Can a clear and concrete example be given?

+4
source share
4 answers

First of all, since jQuery borrows both > and + from CSS, they behave the same way as described in the Selectors spec ; see affiliated combinator and neighboring cathedral combinator .


“Children” refers to items nested one level inside another item. To emphasize the limitation of immediate investment, they may be referred to as “immediate children,” as in the documentation, but they mean the same thing. Elements contained in any depth of nesting are called "descendants"; these are children, grandchildren, great-grandchildren, etc.

The selector E>F will correspond only to the element F in the following structure:

 <E> <F></F> </E> 

But not in the following structure (which will correspond to EF , D>F or even E>D>F ):

 <E> <D> <F></F> </D> </E> 

A more realistic illustration can be found in this answer . As already mentioned, although it covers CSS, it is the same since jQuery still takes it from CSS.


“Brothers and sisters” refers to elements at the same nesting level; that is, elements that are children of the same parent element. There may be next / next siblings and previous / previous siblings if they all have the same parent element, but in this case the elements F , which are preceded by the elements E , refer to the elements F that come immediately after the elements E , without any other elements in between.

The E+F selector will only match the F element in the following structure:

 <E></E> <F></F> 

But not in the following structure (which will correspond to E~F , D+F or even E+D+F ):

 <E></E> <D></D> <F></F> 

A more realistic illustration can be found in this answer .


Finally, here is a more complex scenario with many elements showing which elements of F mapped to 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> 
+8
source

E> F = parent> selected

 <parent> <selected /> </parent> 

E + F = previous_sibling + selected

 <parent> <preceding_sibling /> <selected /> </parent> 
+2
source

The following DOM structure should explain the difference between a sister and a child:

 -- Element -- Sibling -- Sibling -- Child -- Another Child -- Sibling 
+1
source

$('E>F').css({fontWeight:'bold'}); = F immediate children E

<E>
<F> Bold Text </F>
<A> <F> </F> </A> // here 'F' is not immediate children from E
</ E>

$('E+F').css({fontWeight:'bold'}); = F like next brother E

<E> </ E>
<F> Bold Text </F>
<A> </ a>
<F> </F> // here 'F' does not precede E

Playgroup

+1
source

All Articles