jQuery add() methodThe 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. SyntaxThis 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. Example1It 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 NowOutput After the execution of the above code, the output will be - After clicking the given button, the output will be - Example2It 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 NowOutput After the execution of the above code, the output will be - After clicking the appendTo button, the output will be - Next TopicjQuery closest() method |