JSON & the DOM

Lesson 4 of 6

Creating and Updating DOM Elements

Reading the DOM only gets you so far, real interactivity means creating, modifying, and removing elements as your data changes.

const list = document.querySelector('#tasks');

const item = document.createElement('li');
item.textContent = 'Learn the DOM';
item.classList.add('task');
item.dataset.done = 'false';

list.append(item);

item.classList.toggle('done');
item.remove();

Like the previous lesson, this needs a real page with a #tasks list, so it's read-only here.

Reading it

  • document.createElement(tag) creates a new, detached element, it doesn't appear on the page until you attach it.
  • .append(node) (or the older .appendChild(node)) inserts a node as the last child of another element.
  • .classList.add/.remove/.toggle manage CSS classes without you having to fiddle with the raw className string.
  • .dataset.done reads or writes a data-done attribute, a clean way to stash small bits of state directly on an element.
  • .remove() deletes the element from the page entirely.

📝 DOM Editing Quiz

Passing score: 70%
  1. 1.Which method creates a brand-new, detached DOM element?

  2. 2.element.classList.____('done') flips a CSS class on and off.

  3. 3.A newly created element is automatically visible on the page as soon as it is created.