Skip to content
UniCircle
EasyConceptualDOM

Selecting and changing DOM elements

Question JS-DOM-003

How do you select, create, change and remove elements in the DOM? Compare getElementById, getElementsByClassName and querySelectorAll.

Show the explanation

Model answer.

Selecting:

  • document.getElementById('cart'): one element by id, fast.
  • document.getElementsByClassName('item'): a live HTMLCollection; it updates automatically as elements are added or removed.
  • document.querySelector('.item') / querySelectorAll('.item'): any CSS selector; querySelectorAll returns a static NodeList (a snapshot).

Creating, changing, removing:

JavaScript
const li = document.createElement('li');
li.textContent = 'Notebook';
li.classList.add('item', 'new');
li.setAttribute('data-id', '42');
document.querySelector('#list').append(li);

li.style.color = 'green';          // inline style
li.classList.toggle('done');       // prefer classes over inline styles
li.remove();                        // take it out of the DOM

When adding many nodes, build them in a DocumentFragment and append once, so the browser lays out the page once rather than per element.

Original UniCircle question. Last reviewed 22 Oct 2026.