jQuery Add

The add() method in jQuery allows you to include additional elements in a jQuery selection. This is useful when you want to apply changes to multiple, unrelated elements in a single statement.

Key Topics

Basic Usage of add()

The add() method adds one or more elements to the current jQuery selection.

$("#element1").add("#element2").css("color", "red");

Explanation: This code applies the CSS property color: red to both #element1 and #element2.

Adding Multiple Elements

You can add multiple elements to a selection using a selector string or an existing jQuery object.

$("#list1").add("#list2, .highlight").css("background-color", "yellow");

Explanation: This code changes the background color of all elements matching #list1, #list2, and elements with the class highlight.

Example: Using add()


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Add Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="box1" style="width: 100px; height: 100px; background-color: lightblue;"></div>
    <div id="box2" style="width: 100px; height: 100px; background-color: lightgreen;"></div>
    <button id="addButton">Apply Red Border</button>

    <script>
        $(document).ready(function() {
            $("#addButton").click(function() {
                $("#box1").add("#box2").css("border", "2px solid red");
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example uses the add() method to apply a red border to two separate elements (#box1 and #box2) simultaneously when the button is clicked.

Key Takeaways

  • Enhanced Selection: Use add() to extend the current selection with additional elements.
  • Multiple Targets: Combine unrelated elements in a single jQuery statement for efficient modifications.
  • Dynamic Updates: Add elements dynamically to apply consistent styles or actions across groups.