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 liveHTMLCollection; it updates automatically as elements are added or removed.document.querySelector('.item')/querySelectorAll('.item'): any CSS selector;querySelectorAllreturns a staticNodeList(a snapshot).
Creating, changing, removing:
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 DOMWhen 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.
