Three Efficient Methods for Appending Multiple DOM Elements in JavaScript

Nov 27, 2025 · Programming · 7 views · 7.8

Keywords: JavaScript | DOM Manipulation | outerHTML | Performance Optimization | Batch Appending

Abstract: This article provides an in-depth exploration of optimized strategies for appending multiple child elements to the DOM tree in JavaScript. Based on high-scoring Stack Overflow answers, it focuses on the combination of outerHTML and innerHTML methods, which serialize HTML fragments to achieve batch appending and avoid performance overhead from multiple appendChild calls. The article also compares DocumentFragment and append() methods in different scenarios, incorporating insertAdjacentHTML techniques from reference materials to offer comprehensive performance comparisons and code examples. Through detailed DOM operation principle analysis and practical case demonstrations, it helps developers choose the optimal DOM update strategy based on specific requirements.

The Problem of Batch Appending in DOM Operations

In web development, frequent DOM operations are one of the main factors affecting page performance. When multiple child elements need to be added to a parent element, the traditional appendChild() method requires multiple calls, leading not only to code redundancy but also potentially triggering browser reflows and repaints. Consider this typical scenario: when a user clicks the "Add" button, a list item containing a checkbox, label, text input, and action buttons needs to be dynamically created.

Batch Appending Using outerHTML

According to high-scoring Stack Overflow answers, we can utilize the outerHTML property of DOM elements to achieve batch appending. The outerHTML property returns a serialized HTML fragment containing the element itself and all its descendants. By concatenating the outerHTML of individual child elements and assigning it to the parent's innerHTML, all child elements can be appended in a single operation.

The original code used five appendChild() calls:

listElement.appendChild(listItem);
listItem.appendChild(listItemCheckbox);
listItem.appendChild(listItemLabel);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);

The optimized code requires only two lines:

listItem.innerHTML += listItemCheckbox.outerHTML + listItemLabel.outerHTML + editButton.outerHTML + deleteButton.outerHTML;
listElement.appendChild(listItem);

This approach consolidates multiple DOM operations into one, reducing the workload on the browser's rendering engine. Note that assigning to innerHTML replaces all existing content within the element, so the += operator is used for appending rather than replacement.

Alternative Approach with DocumentFragment

DocumentFragment provides a lightweight document object that can serve as a temporary container for assembling DOM nodes. Using DocumentFragment allows building complex DOM structures in memory before adding them to the document with a single operation.

var documentFragment = document.createDocumentFragment();
documentFragment.appendChild(listItem);
listItem.appendChild(listItemCheckbox);
listItem.appendChild(listItemLabel);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
listElement.appendChild(documentFragment);

Although this method still requires multiple appendChild() calls, these operations occur within the document fragment and do not trigger browser reflow until the entire fragment is added to the actual DOM.

Application of Modern append() Method

Modern browsers provide the append() method, which supports adding multiple nodes at once. Compared to appendChild(), the append() method can accept multiple parameters and can also take text nodes in string form.

listElement.append(listItem, listItemCheckbox, listItemLabel, editButton, deleteButton);

This method offers concise syntax but requires attention to browser compatibility issues. In scenarios requiring support for older versions of IE or Edge, polyfills or fallback solutions may be necessary.

HTML String Approach with insertAdjacentHTML

As mentioned in the reference article, the insertAdjacentHTML() method can directly insert HTML strings, which is particularly useful for content from templates or server-side rendering. Using the beforeend position parameter inserts content at the end of the parent element.

const fruitList = document.getElementById("fruit");
fruitList.insertAdjacentHTML("beforeend", `
<li>Pear</li>
<li>Orange</li>
<li>Grape</li>
`);

Combined with template literals, complex HTML structures can be easily built. The advantage of this method is avoiding the tedious process of manually creating DOM elements, but the drawback is difficulty in directly manipulating individual element properties and events.

Performance Comparison and Best Practices

In actual projects, choosing which method to use requires considering multiple factors:

  1. Performance Requirements: For large lists requiring frequent updates, DocumentFragment typically provides the best performance
  2. Code Maintainability: The append() method offers concise syntax that is easy to understand and maintain
  3. Browser Compatibility: The outerHTML approach has the best compatibility, suitable for projects needing to support older browsers
  4. Functional Requirements: If individual element property manipulation or event listener addition is needed, manual DOM element creation is necessary

The outerHTML-based method performs well in most modern browsers, particularly in scenarios requiring batch updates without immediate need to manipulate individual elements. By reducing the number of DOM operations, page responsiveness can be effectively improved, especially on mobile devices or in low-performance environments.

Complete Implementation Example

Here is a complete runnable example demonstrating how to optimize the original code using the outerHTML method:

function addNewItem(listElement, itemText) {
  var listItem = document.createElement("li");
  var listItemCheckbox = document.createElement("input");
  var listItemLabel = document.createElement("label");
  var editableInput = document.createElement("input");
  var editButton = document.createElement("button");
  var deleteButton = document.createElement("button");

  // Set element properties
  listItemCheckbox.type = "checkbox";
  editableInput.type = "text";
  editButton.textContent = "Edit";
  editButton.className = "edit";
  deleteButton.textContent = "Delete";
  deleteButton.className = "delete";
  listItemLabel.textContent = itemText.value;

  // Batch append using outerHTML
  listItem.innerHTML += listItemCheckbox.outerHTML + listItemLabel.outerHTML + 
                       editableInput.outerHTML + editButton.outerHTML + 
                       deleteButton.outerHTML;
  listElement.appendChild(listItem);

  // Clear input field
  if (itemText.value.length > 0) {
    itemText.value = "";
    itemText.focus();
  }
}

This implementation not only solves the problem of repeated appendChild() calls but also maintains code readability and functionality. In practical applications, the most suitable DOM operation strategy can be chosen based on specific requirements.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.