Skip to content

jQuery append multiple elements

  • by

To append multiple elements using jQuery, you can pass multiple arguments to the append() method. Each argument represents an element or a collection of elements that you want to append.

The syntax for appending multiple elements using jQuery’s append() method is as follows:

$(parentElement).append(element1, element2, ...);
  • $(parentElement): This selects the parent element to which you want to append the elements. You can use any valid CSS selector or a jQuery object to specify the parent element.
  • .append(element1, element2, ...): This is the append() method, which appends one or more elements to the selected parent element. You can pass multiple arguments, separated by commas, representing the elements you want to append.
// Appending multiple elements to a parent element with id "myDiv"
$('#myDiv').append(element1, element2, element3);

jQuery append multiple elements example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Append Multiple Elements</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="myDiv">
    <p>This is a paragraph.</p>
  </div>

  <script>
    $(document).ready(function() {
      var element1 = $('<p>Element 1</p>');
      var element2 = $('<p>Element 2</p>');
      var element3 = $('<p>Element 3</p>');

      $('#myDiv').append(element1, element2, element3);
    });
  </script>
</body>
</html>

Output:

jQuery append multiple elements

jQuery creates and appends multiple elements

To create and append multiple elements using jQuery, you can use a combination of the $() function and the appendTo() method. The $() function allows you to create new elements, and the appendTo() method appends those elements to a target element.

Here’s an example that demonstrates how to create and append multiple elements using jQuery:

<!DOCTYPE html>
<html>
<head>
  <title>Create and Append Multiple Elements</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="myDiv">
    <p>This is a paragraph.</p>
  </div>

  <script>
    $(document).ready(function() {
      var element1 = $('<p>Element 1</p>');
      var element2 = $('<p>Element 2</p>');
      var element3 = $('<p>Element 3</p>');

      element1.appendTo('#myDiv');
      element2.appendTo('#myDiv');
      element3.appendTo('#myDiv');
    });
  </script>
</body>
</html>

Do comment if you have any doubts or suggestions on this jQuery code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading