Learning jQuery Siblings Method - .siblings()

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.

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.

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 ‘first’, in such a way that only those having css class 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.

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.