jQuery add() method with Example



The add() method in jQuery is used to add elements to an existing group of elements.

Syntax

The syntax is as follows −

$(selector).add(ele,context)

Above, ele is the selector expression, whereas context specifiesfrom where the selector expression should begin matching.

Example

Let us now see an example to implement the jQuery add() method −

<!DOCTYPE html>
<html>
<head>
<style>
   .one {
      color: white;
      background-color: blue;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("h2").add("p").addClass("one");
   });
</script>
</head>
<body>
<h1>Products</h1>
<h2>Out-of-stock products</h2>
<p>Let us now see some products.</p>
<span>We had Accessories</span><br>
<span>We also had Books, which are now out-of-stock.</span><br>
<p>Electronics products sold completely.</p>
</body>
</html>

Output

This will produce the following output −

Example

Let us now see another example −

<!DOCTYPE html>
<html>
<head>
<style>
   .one {
      color: white;
      background-color: orange;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("h1").add("h2").add("p").addClass("one");
   });
</script>
</head>
<body>
<h1>Products</h1>
<h2>Out-of-stock products</h2>
<p>Let us now see some products.</p>
<span>We had Accessories</span><br>
<span>We also had Books, which are now out-of-stock.</span><br>
<p>Electronics products sold completely.</p>
</body>
</html>

Output

This will produce the following output −


Advertisements