jQuery – Child and Sibling Selectors example
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>
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");
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");
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");
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");
Hope you have more understand about the jQuery selectors now.
Well I’m adding this RSS to my e-mail and could look out for a lot more of your respective interesting content. Make sure you update this again very soon..
Awesome tutorial but instead of taking screenshots why not just put interactive javascript with buttons to toggle the borders on/off for different groups?
Hi, thanks for the tutorial.
I wanted to know how can we create relationships between two divs so that they become siblings.
I have two divs:
Any Ideas? And I don’t want to change the id names (home, about)