jquery
  1. jquery-add

JQuery add()

The add() method in jQuery is used to add one or more elements to the selected set of elements. It can be used to add new content to the DOM or to modify existing content.

Syntax

The basic syntax for the add() method is as follows:

$(selector).add(content, context);
  • selector: The jQuery selector that selects the initial set of elements.
  • content: The content to add to the selected set of elements.
  • context: The context in which to search for the content parameter.

Use

The add() method is useful when you want to add new content to an existing DOM selection. It can also be used to create a new selection that combines multiple selections.

Example

Here is an example of using the add() method to add a new div element to an existing selection:

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("p").add("div").css("background-color", "yellow");
    });
  </script>
</head>
<body>

  <p>This is a paragraph.</p>
  <p>This is another paragraph.</p>
  <p>This is a third paragraph.</p>

</body>
</html>
Try Playground

In this example, we use the add() method to select all p elements and then add a new div element to the selection. We then use the css() method to set the background color of all selected elements to yellow.

Summary

The add() method is a powerful jQuery method that allows you to add new content to the DOM or to modify existing content. It can be used to create new selection sets that combine multiple selections, making it a useful tool for web developers. With its simple syntax and wide range of applications, the add() method is a great addition to any developer's toolkit.

Published on: