The add method
The add method adds the given elements to an existing set of elements.
Syntax
Adding by selector:
.add(selector);
The elements to be added are specified by one or more (array) DOM elements:
.add(DOM element);
The elements to add are specified by the jQuery object:
.add(jQuery object);
The added elements are specified by html text:
.add(html text);
The elements to add are searched for on the page using the given selector, within the scope specified by the second parameter. The search scope can be a DOM element, a jQuery object, or a document object:
.add(selector, context);
Example
Let's find all the paragraphs, put the text '!' at the end of them, then add headings h2 to the found paragraphs and set the color red for both headings and paragraphs:
<div>ddd</div>
<h1>hhh</h1>
<p>ppp</p>
<div id="test"><h2>hhh</h2></div>
<p>ppp</p>
<h2>hhh</h2>
<p>ppp</p>
$('p').append('!').add('h2').css('color', 'red');
Example
Let's introduce a search context - we'll add only those h2 that lie inside the #test element:
let $context = $('#test');
$('p').append('!').add('h2', $context).css('color', 'red');
Example
Let's create a search context in the form of a DOM element using the JavaScript method querySelector:
let context = document.querySelector('#test');
$('p').append('!').add('h2', context).css('color', 'red');
Example
Most often, you can do without context, simply by making a more complex selector:
$('p').append('!').add('#test h2').css('color', 'red');