Adding and Removing Elements

createElement, appendChild, prepend, removeChild, remove

Back to Exercises

Playground

Items will appear here...

const container = document.getElementById('bucket'); const item = document.createElement('div'); item.textContent = 'New Item'; item.className = 'chip'; container.appendChild(item); // container.prepend(item); // container.removeChild(container.lastElementChild); // item.remove();

Full Code Used in This Demo

HTML

<div id="bucket"></div>
<button onclick="addItem()">Add Item</button>
<button onclick="prependItem()">Prepend Item</button>
<button onclick="removeLast()">Remove Last</button>
<button onclick="clearAll()">Clear All</button>

CSS

.bucket { border: 2px dashed #cbd5e1; border-radius: 8px; padding: 10px; }

JavaScript

function addItem() {
  const container = document.getElementById('bucket');
  const item = document.createElement('div');
  item.className = 'chip';
  item.textContent = 'Item';
  container.appendChild(item);
}