How to Adds elements to the set of matched elements in jQuery ?
In jQuery, we can add elements to the set of matched elements using the add()
method. This method creates a new jQuery object that includes the original set of matched elements as well as the additional elements specified as parameters.
Syntax:
$(selector).add(element)
Here, selector
is the initial set of matched elements and element
is the additional element(s) to be added to the set.
Example 1: Suppose we have a set of matched elements that represent all the paragraphs on a page. We can add the element with ID "my-paragraph" to this set using the following code:
$("p").add("#my-paragraph");
Example 2: We can also add multiple elements to the set by specifying them as separate parameters:
$("p").add("#my-paragraph", ".intro");
This will add the element with ID "my-paragraph" as well as all elements with class "intro" to the set of matched elements.
Example 3: We can also add elements dynamically using a callback function. The function should return the element(s) to be added:
$("p").add(function() {
return $(this).prev();
});
This will add the previous sibling of each paragraph to the set of matched elements.
Overall, the add()
method provides a flexible way to add elements to a set of matched elements in jQuery.