jQuery | andSelf( ) with Examples

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:

andSelf( )(selector);

Parameters: It does not accept any parameter.
Return Value: It returns all added element against the specified selector.
jQuery code to show the working of andSelf( ) method:

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <script type="text/javascript" 
    </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>

chevron_right


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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.