jQuery child and sibling selectors can divide into four selectors, descendant selector (A B), child selector (A > B), adjacent sibling selector (A + B) and general sibling selector (A ~ B). Let go through an example to understand the different in between.

Firstly, you have to understand what are child and sibling. Let’s see this example,

<h1>Child and Sibling Selectors example</h1>
<div class="person1">
	<div class="child">
		<div class="grandchild">
			<div class="great-grandchild">
				I'm the great grandchild.
			</div>
			I'm the grandchild.
		</div>
		I'm the first child.
	</div>
 
	<div class="child">
		I'm the second child.
	</div>
 
	<div class="child">
		I'm the third child.
	</div>
	I'm person1
</div>
<p class="person2">I'm person2</p>
<p class="person3">I'm person3</p>
jquery-child-sibling-example

All the <div> elements that under <div class=”person1″> element are its child. And the “person1″, “person2″ and “person3″ are in sibling relationship.

1. Descendant selector (A B)

Descendant selector is used to select all elements matched by “B” that are child, grandchild, great-grandchild, great-great-grandchild..(any levels deep) of a “A” element.

$(".person1 div").css("border", "2px solid red");
jquery-child-sibling-example-descendant-selector

2. Child selector (A > B)

Child selector is used to select all elements matched by “B” that are child of a “A” element.

$(".person1 > div").css("border", "2px solid red");
jquery-child-sibling-example-child-selector

3. Adjacent sibling selector (A + B)

Adjacent sibling selector is used to select the immediately follow or next elements matched by “B” that is a sibling of a “A” element.

$(".person1 + p").css("border", "2px solid red");
jquery-child-sibling-example-Adjacent-sibling

4. General sibling selector (A ~ B)

General sibling selector is used to select all elements matched by “B” that is a sibling of a “A” element.

$(".person1 ~ p").css("border", "2px solid red");
jquery-child-sibling-example-general-sibling

Hope you have more understand about the jQuery selectors now.

Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts