Hiprup

What is the difference between createElement and innerHTML?

Two ways to add content to the DOM, with trade-offs.

  • createElement — build nodes programmatically and append them. Safe (no HTML parsing) and keeps references, but more verbose.

  • innerHTML — set markup from a string. Quick, but re-parses, can break event listeners, and risks XSS with untrusted input.

Prefer createElement (or templates) for dynamic, user-driven content; reserve innerHTML for trusted, static markup.

// createElement — safe, programmatic
const li = document.createElement('li');
li.textContent = userInput; // SAFE — no HTML parsing
li.className = 'item';
document.getElementById('list').appendChild(li);

// innerHTML — parses HTML (XSS risk!)
document.getElementById('list').innerHTML += `<li class="item">${userInput}</li>`;
// If userInput = '<script>alert(1)</script>' → XSS!

// innerHTML — replaces everything (destroys listeners)
container.innerHTML = '<div>New content</div>';
// All previous children and their event listeners are GONE

// insertAdjacentHTML — best of both (adds without replacing)
list.insertAdjacentHTML('beforeend', '<li>Safe static content</li>');
// Adds to end without destroying existing elements

createElement + textContent is safe (no HTML parsing). innerHTML parses HTML (XSS vulnerable with user data) and replaces all content (destroying event listeners). insertAdjacentHTML adds HTML at a specific position without replacing existing content — useful for static HTML additions.

createElement + textContent = safe (no XSS). innerHTML = parses HTML (XSS risk) + replaces everything (kills event listeners). insertAdjacentHTML = adds without replacing. For user data: ALWAYS createElement.

For static HTML: innerHTML or insertAdjacentHTML are acceptable.

What is the difference between createElement and innerHTML? | Hiprup