Open In App

How to select all sibling elements of an element using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to select all sibling elements of an element using jQuery. To select all sibling elements of an element, we will use the siblings() method

The siblings() method is used to find all sibling elements of the selected element. The siblings are those having the same parent element in DOM Tree. 

Syntax:

$(selector).siblings(function)

This function accepts an optional parameter “function” that is going to select all siblings of the selected elements. It returns all the siblings of the selected element.

Approach: First, we will create the main div container, and inside the main container, we will add two div containers. When the user clicks on the button, the siblings() method is called and it selects the siblings of the section1 class container. After selecting the siblings, we add some CSS properties to them.

Example: In this example, we will use the above approach.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">     
    <script src=
    </script>
    <title>
        How to select all sibling elements
        of an element using jQuery?
    </title>
 
    <style>
        .main {
            width: 450px;
            text-align: justify;
            font-size: 18px;
        }
        #GFG {
            padding: 5px 15px;
            margin-top: 20px;
        }
        .Geeks {
            font-size: 18px;
            font-weight: bold;
            color: green;
        }
    </style>
    <script>
        $(document).ready(function () {
            $("#GFG").on('click', function () {
                $(".section1").siblings().addClass("Geeks");
            });
        });
    </script>
</head>
<body>
    <center>
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <h3>
            How to select all sibling elements
            of an element using jQuery?
        </h3>
        <div class="main">
            <div class="section1">
                HTML stands for HyperText Markup
                Language. It is used to design
                web pages using a markup language.
                HTML is the combination of
                Hypertext and Markup language.
            </div>
            <div class="section2">
                Cascading Style Sheets, fondly
                referred to as CSS, is a simply
                designed language intended to
                simplify the process of making
                web pages.
            </div>
        </div>
        <input type="button" id="GFG"
            value="Remove Contents">
    </center>
</body>
</html>


Output: 



Last Updated : 02 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads