agyanadda@gmail.com

JS Create and Remove Elements

Working with the Page 1 min read Updated Dec 1, 2026 Topic 26 of 38

JavaScript can build new elements and add them to the page.

Create and add

const li = document.createElement('li');
li.textContent = 'New item';
document.querySelector('ul').append(li);
  • append(el) — add at the end of a parent
  • prepend(el) — add at the start
  • el.before(x) / el.after(x) — add next to an element

Remove

el.remove();

Insert HTML quickly

parent.insertAdjacentHTML('beforeend', '<li>Item</li>');

Tip

When building many elements, create them first and add them in one step to keep the page fast.

Example

Example — To-do list HTML
<style>
  li { margin: 4px 0; }
  li button { margin-left: 8px; color: crimson; border: none; background: none; cursor: pointer; }
</style>

<input id="task" placeholder="New task">
<button id="add">Add</button>
<ul id="todos"></ul>

<script>
  const list = document.getElementById('todos');
  const input = document.getElementById('task');

  document.getElementById('add').addEventListener('click', () => {
    const text = input.value.trim();
    if (!text) return;

    const li = document.createElement('li');
    li.textContent = text;

    const del = document.createElement('button');
    del.textContent = '✕';
    del.addEventListener('click', () => li.remove());

    li.append(del);
    list.append(li);
    input.value = '';
  });
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method creates a new element?

Exercise 2 Fill in the Blank

el.___() deletes an element from the page.

Exercise 3 True / False

prepend() adds an element at the start of the parent.

Frequently Asked Questions

createElement with textContent is safer with user input. innerHTML is quicker for trusted, fixed HTML.