innerHTML vs insertAdjacentHTML in JavaScript

Both innerHTML and insertAdjacentHTML are popular JavaScript methods used to insert HTML markup into the Document Object Model (DOM). While innerHTML reads or replaces the entire content inside a target element, insertAdjacentHTML injects HTML markup at a specific position relative to the element without destroying existing child nodes. Understanding how these two methods work is crucial for writing efficient JavaScript that maintains application state and avoids performance bottlenecks.

How innerHTML Works

The innerHTML property gets or sets the HTML markup contained within an element. When you assign a new value to element.innerHTML, the browser removes all existing child nodes, parses the new HTML string, and builds new DOM elements inside the container.

const container = document.getElementById('container');

// Replaces all existing content
container.innerHTML = '<p>New content</p>';

// Appends content (anti-pattern)
container.innerHTML += '<p>Appended content</p>';

When you use += with innerHTML, the browser does not simply append the new markup. Instead, it serializes the existing DOM back into an HTML string, concatenates the new string, destroys the old DOM nodes, and re-parses the entire combined string into new nodes. This process destroys any event listeners, selected states, or references attached to the existing children.

How insertAdjacentHTML Works

The insertAdjacentHTML() method parses a specified text as HTML and inserts the resulting nodes directly into the DOM tree at a specified position. It takes two arguments: the position string and the HTML string.

The four available positions are: * 'beforebegin': Before the element itself. * 'afterbegin': Just inside the element, before its first child. * 'beforeend': Just inside the element, after its last child. * 'afterend': After the element itself.

const container = document.getElementById('container');

// Inserts a new paragraph at the end of the container
container.insertAdjacentHTML('beforeend', '<p>Appended content</p>');

Because insertAdjacentHTML does not alter existing elements, it does not re-parse the target container or destroy existing DOM nodes. Consequently, all previously attached event listeners and element states remain intact.

Key Differences

1. DOM Re-parsing and Event Listeners

2. Performance

3. Placement Flexibility

When to Use Each

Use innerHTML when you intentionally want to clear out an element’s entire contents and replace them with new markup.

Use insertAdjacentHTML when you need to append, prepend, or insert HTML relative to an existing element without affecting existing children, their event listeners, or application performance.