Skip to content

jQuery append array of elements

  • by

If you have an array of elements and you want to append them to a target element using jQuery, you can utilize the append() function with the spread operator (...) to achieve the desired result.

Here’s an example of the syntax for appending an array of elements using jQuery:

// Array of elements to append
var elements = [
  $('<div>Element 1</div>'),
  $('<div>Element 2</div>'),
  $('<div>Element 3</div>')
];

// Target container element
var container = $('#container');

// Append the array of elements to the container
container.append(...elements);

jQuery append array of elements example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Append Array of Elements Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      // Array of elements to append
      var elements = [
        $('<div>Element 1</div>'),
        $('<div>Element 2</div>'),
        $('<div>Element 3</div>')
      ];

      // Target container element
      var container = $('#container');

      // Append the array of elements to the container
      container.append(...elements);
    });
  </script>
</head>
<body>
  <div id="container">
    <!-- Existing content in the container -->
  </div>
</body>
</html>

Output:

jQuery append array of elements

In the <head> section, we include a <script> tag that references the jQuery library from the official CDN (Content Delivery Network) using the URL https://code.jquery.com/jquery-3.6.0.min.js.

If you have an array of elements that you want to append to a container element, you can iterate over the array and append each element individually.

// Array of elements to append
var elements = [
  $('<div>Element 1</div>'),
  $('<div>Element 2</div>'),
  $('<div>Element 3</div>')
];

// Target container element
var container = $('#container');

// Append each element to the container
$.each(elements, function(index, element) {
  container.append(element);
});

By iterating over the array using $.each(), we can access each element and append it to the container using the append() function.

After running this code, the container element will contain the three div elements from the elements array.

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

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

Your email address will not be published. Required fields are marked *