HI WELCOME TO KANSIRIS

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

1
$(selector).siblings(filter)
filter is an optional parameter to narrow down the siblings search.

Example 1: jQuery Siblings

Check the code below, there are 3 li which are siblings. They have a same parent – ul.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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.
1
$("#myLi").siblings().css({ "color": "aquamarine", "border": "solid 2px #0184e3" });
This will add background color to the 2nd and the 3rd li elements.

Example 1: jQuery Siblings with filter parameter

Now I will use the filter parameter with the jQuery Siblings method.
Consider the below code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<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 ‘first’, in such a way that only those having css class select get selected. This jQuery Siblings code will be:
1
$("#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.