Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to create an element and add it to the page

Short answer

document.createElement() creates an element, and append() adds it to the end of a parent:

<ul id="list"></ul>
<script>
  const item = document.createElement('li');
  item.textContent = 'Buy milk';
  item.className = 'task';
  document.getElementById('list').append(item);
</script>

A list from an array

Create an element for each item of the array and add them all at once:

<ul id="users"></ul>
<script>
  const users = ['Anna', 'Oleg', 'Maria'];
  const items = users.map((name) => {
    const li = document.createElement('li');
    li.textContent = name;
    return li;
  });
  document.getElementById('users').append(...items);
</script>

Other positions

prepend() adds to the beginning, before() and after() put the element next to another one:

list.prepend(firstItem);
title.after(subtitle);

Common mistake

Building elements with innerHTML += re-creates all the content each time: old event handlers are lost, and user text can inject HTML. Use createElement() and textContent.

// bad
list.innerHTML += `<li>${userInput}</li>`;

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.