Javatpoint Logo
Javatpoint Logo

jQuery add() method

The add() method in jQuery adds an element to the set of existing elements. We can use this method to add the elements inside the context elements if the context parameter is specified, or can use it to add elements in the entire document.

Do not assume that the add() method is used to append the elements to the set of existing elements. This method does not work similar to the append() method. It should not be compared with the append() method.

Syntax

This method accepts two parameters in which one is mandatory and the other is optional. The parameter values of the add() method are defined as follows:

element: It is a mandatory parameter. It can be a jQuery object, a selector expression, an HTML snippet, an element or the set of elements to be added to the set of existing elements.

context: It is an optional parameter. It indicates the point in the document at which the selector starts matching.

Let's understand the add() method using some illustrations.

Example1

It is a simple example of using the add() method. Here we are using the add() method to add the same CSS style for both p and span elements. Here, there are some p elements and some span elements, and both get styled on clicking the given button.

Test it Now

Output

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

JQuery add() method

After clicking the given button, the output will be -

JQuery add() method

Example2

It is another example of using the add() method. Here, we are using the appendTO() method as well as the add() method in order to specify the comparison between them. There are two buttons named as appendTo and add. When we click the appendTo button, a new element will be inserted, while on clicking the add button, no element will insert.

On every click of the appendTo button, a new paragraph element will be added after the div element.

Test it Now

Output

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

JQuery add() method

After clicking the appendTo button, the output will be -

JQuery add() 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