Javatpoint Logo
Javatpoint Logo

jQuery andSelf() method

The andSelf() method in jQuery is used to add the previous set of elements to the current set. Objects in jQuery maintain an internal stack that keeps track of changes to the matched set of elements. The andSelf() method helps when we require the previous set of elements. It is an inbuilt method in jQuery.

This method is useful when we have multiple traversals in the script, and we have to add something that was matched before the last traversal.

The andSelf() is deprecated in jQuery, we can use addBack() method instead. It is completely removed in jQuery version 3.0. We can use the jQuery version 2.1.3 to see the working of the andSelf() method.

Syntax

The commonly used syntax of this method is given below -

This method is used without any argument, as it does not accept any argument.

Let's see some illustrations of using the andSelf() method.

Example1

In this example, we are applying the andSelf() method to the paragraph element with id = "p1". Here, we are also using the nextAll() method to select the next paragraph siblings of the paragraph element with id = "p1".

We are using the jQuery version 2.1.3, it is because the andSelf() method will not work for the current jQuery version.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery andSelf() method

After clicking the given button, the output will be -

jQuery andSelf() method

Example2

Here, we are showing the two div's in which the first div is used without applying andSelf() method, and in the second div, we are applying the andSelf() method. In the output, we will see the two divs, including the paragraph elements. Without using the andSelf() method, only the paragraph elements will be selected, while after using the andSelf() method, the div will also get selected along with the paragraph elements.

We are using the jQuery version 2.1.3, it is because the andSelf() method will not work for the current jQuery version.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery andSelf() method




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA