Skip to main content
JavaScript & the browser·Module C2 · Lesson 7
TaskHTML has <ul id='list'></ul>. Given const items = ['apple', 'banana', 'cherry'], use createElement + textContent + appendChild in a forEach to render three <li> items inside #list. Safe by default — no innerHTML.

Creating elements: createElement vs innerHTML

100 XP8 min
Theory

Three ways to add HTML to the page

// 1. createElement — verbose, safe, fast on big lists
const li = document.createElement("li");
li.textContent = "Anna";
ul.appendChild(li);

// 2. innerHTML — compact, dangerous with user input, parses HTML
ul.innerHTML = "<li>Anna</li>";

// 3. insertAdjacentHTML — middle ground (no full re-parse of the parent)
ul.insertAdjacentHTML("beforeend", "<li>Anna</li>");

When each one fits

  • createElement + textContent — adding ONE element where the data comes from a user. Always safe (no XSS, no script execution).
  • innerHTML — first paint of a static block from your own template literal. Avoid for user input. If you must, sanitize first.
  • insertAdjacentHTML — appending to a long list without re-rendering siblings. Good middle ground.

The "always set textContent" rule

When the data comes from anywhere outside your code — a fetch response, a query string, a form input — write it via textContent. The DOM treats it as plain text and the user sees exactly what they typed. innerHTML would interpret <script> as a script tag. (See html-a3-20 in the HTML track for the XSS lesson.)

The "build, then insert" pattern

const fragment = document.createDocumentFragment();
items.forEach(item => {
  const li = document.createElement("li");
  li.textContent = item;
  fragment.appendChild(li);
});
list.appendChild(fragment);   // one DOM mutation, not N

DocumentFragment is a free in-memory container. Building 100 <li>s into a fragment and inserting once is 10× faster than appending each <li> individually. Senior-level move.

🔒

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial — card required, cancel anytime.

Sign up — free trial →

First 10 lessons in each track are free. No card needed for those.

PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.