const header =document.querySelector("h1");const buttons =document.querySelectorAll(".btn");const main =document.getElementById("main-content");// querySelectorAll returns a static NodeList
buttons.forEach(btn =>{console.log(btn.textContent);});
Note querySelector returns the first match or null. querySelectorAll returns a static NodeList (does not auto-update). Use Array.from() if you need full array methods.
Note append() accepts multiple nodes and strings. appendChild() only accepts one node. Prefer textContent over innerHTML to prevent XSS when inserting user-provided text.
create elementadd elementappendChildinsert DOMbuild DOM
Note The third argument can be a boolean (useCapture) or an options object { capture, once, passive, signal }. Use { once: true } for one-shot handlers.
Note Attach one listener to a parent instead of many on children. Works for dynamically added elements too. Use closest() to find the nearest matching ancestor.
event delegationdelegate eventsparent listenerdynamic elements eventsclosest
const output =document.querySelector("#output");// textContent: safe, treats everything as text
output.textContent="<b>Hello</b>";// shows literal "<b>Hello</b>"// innerHTML: parses HTML (XSS risk with user input!)
output.innerHTML="<b>Hello</b>";// shows bold Hello// Safe alternative for HTMLconst tmpl =document.createElement("template");
tmpl.innerHTML="<b>Hello</b>";
output.append(tmpl.content.cloneNode(true));
Note NEVER use innerHTML with unsanitized user input -- it is the #1 source of XSS vulnerabilities. Use textContent for plain text and createElement for dynamic HTML.
innerHTMLtextContentXSS preventionset HTMLinsert text
const item =document.querySelector(".active-item");console.log(item.parentElement);// parentconsole.log(item.children);// HTMLCollection of childrenconsole.log(item.nextElementSibling);// next sibling elementconsole.log(item.closest(".container"));// nearest ancestor matching selector
Note Use element-based properties (parentElement, children) over node-based ones (parentNode, childNodes) to skip text/comment nodes.
DOM traversalparent elementchild elementssiblingclosest ancestor
Removing Elements
Syntax
element.remove()
parent.removeChild(child)
Example
// Modern: element removes itselfconst notification =document.querySelector(".notification");
notification.remove();// Remove all childrenconst container =document.querySelector("#list");while(container.firstChild){
container.removeChild(container.firstChild);}// Faster: clear all children
container.replaceChildren();
Note el.remove() is cleaner than parentNode.removeChild(el). Use replaceChildren() with no arguments to efficiently clear all children.
remove elementdelete DOM elementclear childrenremove from DOM