Saltar al contenido principal
← ⚡ JavaScript & the browser·Módulo C2 · Lección 7
TareaHTML 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.

Creando elementos: createElement vs InnerHTML

100 XP8 min
Teoría

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.

🔒

Regístrate para empezar a programar

La teoría está abierta a todos. El editor, la vista previa y el check se desbloquean con una prueba gratis de 7 días — se requiere tarjeta, cancela cuando quieras.

Registrarse — prueba gratis →

Las primeras 10 lecciones de cada ruta son gratis. No se necesita tarjeta.

← AnteriorSiguiente lección →

Recibe un consejo de Python o web al día — por email

Corto, escrito a mano, sin spam. Anula la suscripción en un clic.