DOM standards and methods
The DOM standard is the specification, maintained by WHATWG, that defines how a web page is represented as a tree of objects and which methods JavaScript can use to find, read and change those objects. Because every modern browser implements the same standard, methods like querySelector, createElement and addEventListener behave the same way everywhere. Knowing the core methods is the step between understanding the DOM tree and actually manipulating a page.
Nodes, elements and the tree
Everything in the tree is a node: the document itself, each element, each piece of text and even comments. Elements are the nodes created from HTML tags, and they are the ones you work with most. Every node has a parent (except the document) and may have children. Properties such as parentElement, children, firstElementChild and nextElementSibling let you move around the tree. Versions without "Element" in the name, like childNodes and nextSibling, include text nodes too, often the whitespace between tags.
Finding elements
| Method | Returns | Notes |
|---|---|---|
document.getElementById('menu') | One element or null | Fast; id without # |
querySelector('.card a') | First match or null | Any CSS selector |
querySelectorAll('li') | Static NodeList | Has forEach; does not update |
getElementsByClassName('item') | Live HTMLCollection | Updates as the DOM changes |
getElementsByTagName('p') | Live HTMLCollection | Same live behaviour |
element.closest('form') | Nearest matching ancestor or itself | Great inside event handlers |
querySelector and querySelectorAll can be called on any element, not just document, which limits the search to that element's descendants.
Always handle the null case. If a selector has a typo or the element is not on the current page, querySelector returns null, and calling a method on it throws "Cannot read properties of null". A quick if (el) check, or the optional chaining operator el?.remove(), keeps one missing element from stopping the whole script.
Creating, changing and removing
const list = document.querySelector('#todo-list');
// Create and insert
const item = document.createElement('li');
item.textContent = 'Buy milk';
item.classList.add('todo');
item.dataset.id = '7'; // sets data-id="7"
list.append(item); // add at the end
list.prepend(document.createElement('hr'));
// Read and change attributes and classes
const link = document.querySelector('a.help');
link.setAttribute('target', '_blank');
console.log(link.getAttribute('href'));
link.classList.toggle('active');
// Replace and remove
const old = list.querySelector('.done');
if (old) old.remove();
append and prepend accept several nodes or strings at once. The older appendChild accepts exactly one node, and insertBefore and removeChild are the older counterparts of the newer methods. You will still see them in older code, and they still work.
For content, textContent sets plain text and is safe with user input. innerHTML parses HTML, which is convenient for trusted templates but dangerous with anything a user typed, since it can run injected scripts.
Live collections cause strange loops
A live HTMLCollection updates instantly when the document changes. If you loop over getElementsByClassName('item') and remove the class from each element, the collection shrinks while you loop, and you end up skipping every other element. HTMLCollections also lack forEach. The fix is to use querySelectorAll, which returns a static snapshot, or convert with Array.from() before looping.
Another frequent issue is running a script before the elements exist. If querySelector returns null, check that the script uses defer or sits at the end of the body.
Takeaway
Use querySelector and querySelectorAll for finding, createElement with append for adding, classList and setAttribute for changing, and remove() for deleting. Prefer textContent over innerHTML unless you control the HTML.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.