Learning jQuery Siblings Method – .siblings()

Learning jQuery Siblings Method – .siblings()

The jQuery Siblings method – .siblings() returns all the siblings of the selected element. Siblings are those elements that have the common parent.

jQuery Siblings – .siblings() Syntax

$(selector).siblings(filter)

filter is an optional parameter to narrow down the siblings search.

There is also a related method called jQuery children which provides all the direct children of any element.

Example 1: jQuery Siblings

Check the code below, there are 3 li which are siblings. They have a same parent – ul.

<ul>
    Parent
    <li id="myLi">
        Siblings
        <label>Grand Child</label>
    </li>
    <li>
        Siblings
        <label>Grand Child</label>
    </li>
    <li>
        Siblings
        <label>Grand Child</label>
    </li>
</ul>

To get all the siblings of myLi, use the below .siblings() code.

$("#myLi").siblings().css({ "color": "aquamarine", "border": "solid 2px #0184e3" });

This will add background color to the 2nd and the 3rd li elements.

Learn how to use jQuery Toggle method – .toggle() by reading this tutorial.

Example 1: jQuery Siblings with filter parameter

Now I will use the filter parameter with the jQuery Siblings method.

Consider the below code.

<ul>
    Parent
    <li id="first">
        Siblings
        <label>Grand Child</label>
    </li>
    <li class="select">
        Siblings
        <label>Grand Child</label>
    </li>
    <li class="select">
        Siblings
        <label>Grand Child</label>
    </li>
    <li>
        Siblings
        <label>Grand Child</label>
    </li>
</ul> 

To select all the siblings of li element having id called first, in such a way that only those having css class called select get selected, this jQuery Siblings code will be:

$("#first").siblings(".select").css({ "color": "aquamarine", "border": "solid 2px #0184e3" });

The above .siblings() code will add border around the 2nd and the 3rd li elements only.

Check the below link:

DOWNLOAD

Selections of elements in the DOM is made quite simple when you use the jQuery Parents method.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate