Header Ads

ad

Introduction of Jquery Traversing (parent, child, siblings concept)


Hello all, this blog will be about the introduction of Jquery Traversing. The word "Traversing" seems to be so harder but if we simplify the word, it is about the parent, child and sibling concept only.

Traversing can be broken into several parts like parent, children as well as siblings.It is much easier to understand the concept. As we all know that jquery is all about selection and action, and this parent-child concept is very essential in jquery. Let us start in detail with examples.

HTML

Let us create a parent child and siblings conceptual html elements like the following.

<div class="grand-parent">
    <div class="parent-1">
        <div class="child-1"></div>
        <div class="child-2"></div>
    </div>
   <div class="parent-2">
        <div class="child-3">
            <div class="sub-child-1"></div>
        </div>
   </div>
   <div class="parent-3"></div>
</div>

Now, we have our html ready, we will select the element by traversing.


Select Parent elements

/* select div.parent-1 */
$('.child-1').parent();

/* select div.child-3 */
$('.sub-child-1').parent();

/* select div.grand-parent, div.parent-2, div.child-3 */
$('.sub-child-1').parents();

/* select div.parent-2 */
$('.sub-child-1').parents('.parent-2');

/* select div.child-3, div.parent-2 but not the div.grand-parent */
$('.sub-child-1').parentsUntil('.grand-parent');

/* select div.grand-parent */
$('.child-1').closest('.grand-parent');


Select Child elements

/* select div.child-1, div.child-2 */
$('.parent-1').children();

/* select div.child-2 */
$('.parent-1').children('.child-2');

/* select div.child-2 */
$('.parent-1 > div:nth-child(2)');

/* select div.parent-3 */
$('.grand-parent > div:nth-child(3)'); or $('.grand-parent > div:last-child');

/* select div.child-3 */
$('.grand-parent').find('.child-3');


Select Sibling elements

/* select div.parent-2 */
$('.grand-parent').find('.parent-1').next();

/* select div.child-2 */
$('.child-1').next();

/* select div.parent-2, div.parent-3 */
$('.parent-1').nextAll();

/* select div.parent-2 */
$('.grand-parent').find('.parent-3').prev();

/* select div.sub-child-1 */
$('.parent-3').prev().children('.sub-child-1');

/* select div.parent-1, div.parent-2 */
$('.parent-3').prevAll();

/* select div.parent-1, div.parent-3 */
$('.parent-2').siblings();


Okay, this is the basic parent-child, siblings concept of Jquery. Hope you like it. Please share this with every one. Thanks  

No comments