Open In App

jQuery | andSelf( ) with Examples

Last Updated : 30 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The andSelf( ) is an inbuilt method in jQuery which is used to add the previous set of elements to the current set. This method adds previous DOM tree elements to the current set and maintains them in the internal stack which will take care of changes to the matched set of elements. Document Object Model(DOM) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree.

Syntax:

selector.andSelf()  

Parameters:

It does not accept any parameter.

Return Value:

It returns all added elements against the specified selector.

Note: The andSelf() method was used in jQuery versions before 1.8 to include the previous set of matched elements in the current set. However, it has been deprecated and replaced by the addBack() method.

Example: This example shows the use of andSelf( ) method for setting the border around the elements.

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript" src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
        </script>
        <script>
            $(document).ready(function () {
                $("div").find("p").andSelf().addClass("border");
            });
        </script>
        <style>
            p,
            div {
                margin: 5px;
                padding: 5px;
            }
    
            .border {
                border: 2px solid green;
            }
    
            .background {
                background: green;
            }
        </style>
    </head>
    
    <body>
        <div>
            <p>This is first paragraph.</p>
            <p>This is second paragraph.</p>
        </div>
    </body>
</html>

Output: Here border would be added to previous selection which is a division and then second selection which is paragraphs.

Example: This example shows the use of andSelf( ) method for setting the background color.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>jQuery andSelf Example</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>

<body>
    <div class="container">
        <p class="first">First Paragraph</p>
        <p class="second">Second Paragraph</p>
        <p class="third">Third Paragraph</p>
    </div>
    <script>
        $(document).ready(function () {
            // Select the first <p>, then the next <p>
          // and include the first <p> using andSelf()
            $('.first').next().andSelf().css('background-color', 'yellow');

        });
    </script>
</body>

</html>

Output:

andSelf

Output



Next Article

Similar Reads

three90RightbarBannerImg