⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

JavaScript DOM – Document Manipulation

JavaScript DOM (Document Object Model) is a document object model that represents HTML/SVG/XML as a tree of nodes in memory. JavaScript can access and modify these nodes. The container with the HTML is described by the Document interface (extended to HTMLDocument for HTML). The Element interface is enhanced into HTMLElement and various subclasses (e.g., HTMLDivElement, HTMLInputElement …). The HTML DOM API allows the management of content, styles, attributes, events, and more. The DOM represents a document as a logical tree. Each branch ends with a node; nodes are objects. Using DOM methods, we can programmatically read and change the structure, styles, or content. We can attach event handlers to nodes, which are triggered by clicks, typing, focuses, etc.

EXAMPLE
RESULT

DOM Object Model

With the DOM object model, JavaScript gains full power to create dynamic, interactive pages.

  1. JavaScript can change all HTML elements on the web page.
  2. JavaScript can change all HTML attributes on the web page.
  3. JavaScript can change CSS styles (via style or classList).
  4. JavaScript can remove existing elements and attributes.
  5. JavaScript can add new elements and attributes.
  6. JavaScript can react to all HTML events.
  7. JavaScript can define and trigger its own custom events.

W3C DOM Standards

The DOM is a W3C standard – a platform- and language-neutral interface for dynamic access and updating of the content, structure, and style of a document. It is divided into:

  1. Core DOM: The standard model for all document types.
  2. XML DOM: The standard model for XML documents.
  3. HTML DOM: The standard model for HTML documents.

Complete DOM Overview (Cheat Sheet)

The table below displays a comprehensive overview of all key DOM concepts, methods, and events. It is divided into sections for easier searching: element selection, navigation, content modification, styles, and a detailed overview of all important DOM events.

Name Description Syntax Example
1. Selecting Elements (Document)
getElementById() Finds and returns the element with the specified ID (unique). Returns a single element or null. document.getElementById("id") const submitBtn = document.getElementById("btn-submit");
querySelector() Returns the FIRST element that matches the specified CSS selector. Extremely flexible. document.querySelector("selector") ▶ Code Example
querySelectorAll() Returns a static list of all elements (NodeList) that match the CSS selector. document.querySelectorAll("selector") ▶ Code Example
getElementsByClassName() Returns a live collection (HTMLCollection) of all elements with the specified class name. document.getElementsByClassName("class") const deleteBtns = document.getElementsByClassName("btn-delete");
getElementsByTagName() Returns a live collection (HTMLCollection) of all elements with the specified tag name. document.getElementsByTagName("tag") const paragraphs = document.getElementsByTagName("p");
2. Modifying Content and Attributes
textContent Reads or sets the text content of the element and its descendants (ignores HTML). element.textContent = "text"; title.textContent = "W3C DOM Standards";
innerHTML Reads or sets the full HTML structure inside the element (beware of XSS security risks). element.innerHTML = "html"; alertBox.innerHTML = "Important notice!";
value Reads or sets the current value of input fields (input, select, textarea). inputElement.value = "value"; const searchVal = document.getElementById("search").value;
setAttribute() Adds a new attribute or changes the value of an existing attribute on the element. element.setAttribute("name", "value") image.setAttribute("src", "images/logo.png");
getAttribute() Returns the current value of a specified attribute on the element (or null if it does not exist). element.getAttribute("name") const linkHref = link.getAttribute("href");
removeAttribute() Removes a specified attribute from the element. element.removeAttribute("name") inputField.removeAttribute("disabled");
dataset Provides access to all custom data attributes (data-*). element.dataset.propertyName const productId = btn.dataset.productId; // data-product-id
3. Modifying CSS Styles and Classes
style Allows direct adding or reading of inline CSS styles (using camelCase notation). element.style.property = "value"; notice.style.backgroundColor = "#ff0000";
classList.add() Adds one or more CSS classes to the element without overwriting existing ones. element.classList.add("class") btn.classList.add("btn-active");
classList.remove() Removes one or more CSS classes from the element. element.classList.remove("class") btn.classList.remove("hidden");
classList.toggle() Toggles a class: if the class exists, removes it; if it does not exist, adds it. element.classList.toggle("class") menu.classList.toggle("open");
classList.contains() Checks whether the element contains a specific CSS class (returns true or false). element.classList.contains("class") if (box.classList.contains("visible")) { ... }
4. Creating and Modifying Structure (DOM Tree)
createElement() Creates a new HTML element in memory, which must then be inserted into the DOM. document.createElement("tag") const newRow = document.createElement("tr");
append() Inserts a set of DOM objects or text nodes at the END of the selected parent. parent.append(child) list.append(newElement);
prepend() Inserts a set of DOM objects or text nodes at the BEGINNING of the selected parent. parent.prepend(child) table.prepend(tableHeader);
remove() Removes the element directly from the DOM tree. element.remove() oldRow.remove();
5. Navigating Between Elements and Nodes
parentElement Returns the direct parent of the selected element. element.parentElement const divWrapper = btn.parentElement;
children Returns a live HTMLCollection of all child elements. element.children const allParagraphs = container.children;
nextElementSibling Returns the next sibling element on the same level. element.nextElementSibling const nextField = currentField.nextElementSibling;
previousElementSibling Returns the previous sibling element on the same level. element.previousElementSibling const label = inputField.previousElementSibling;
6. Event Management (Mechanics)
addEventListener() Attaches an event listener to an element. element.addEventListener("event", function) ▶ Code Example
removeEventListener() Removes an event listener from an element. element.removeEventListener("event", function) window.removeEventListener("resize", refreshMenu);
preventDefault() Prevents the default behavior of the event (e.g., prevents page reload upon form submission). event.preventDefault() e.preventDefault();
stopPropagation() Prevents the further propagation (bubbling) of the event up the DOM tree. event.stopPropagation() e.stopPropagation();
target Returns the element that actually triggered the event (excellent for event delegation). event.target const selected = e.target;
→ Mouse Events
click Fires when the user clicks (presses and releases a button) on an element. element.addEventListener("click", fn) btn.addEventListener("click", () => { ... });
dblclick Fires when the user double-clicks on an element. element.addEventListener("dblclick", fn) image.addEventListener("dblclick", enlargeImage);
mousedown / mouseup mousedown when a mouse button is pressed; mouseup when a mouse button is released. element.addEventListener("mousedown", fn) window.addEventListener("mousedown", startMove);
mousemove Fires continuously whenever the mouse pointer moves inside an element. element.addEventListener("mousemove", fn) canvas.addEventListener("mousemove", drawCurve);
mouseenter / mouseleave Fire when the mouse enters or leaves an element (does NOT bubble to child elements). element.addEventListener("mouseenter", fn) wrapper.addEventListener("mouseenter", showToolbar);
mouseover / mouseout Similar to enter/leave, but they bubble (triggering also when moving onto child elements). element.addEventListener("mouseover", fn) menu.addEventListener("mouseover", openSubmenu);
contextmenu Fires when the mouse is right-clicked (before the system context menu appears). element.addEventListener("contextmenu", fn) area.addEventListener("contextmenu", (e) => e.preventDefault());
→ Keyboard Events
keydown Fires the moment the user presses any key on the keyboard. element.addEventListener("keydown", fn) inputField.addEventListener("keydown", (e) => { if(e.key === "Enter") search(); });
keyup Fires when the user releases a pressed key on the keyboard. element.addEventListener("keyup", fn) searchBox.addEventListener("keyup", filterResults);
keypress (Deprecated, use keydown instead) Fired when a key that produces a character value was pressed. element.addEventListener("keypress", fn) inputField.addEventListener("keypress", fn);
→ Form and Input Field Events
submit Fires on a <form> element when the user submits a form. form.addEventListener("submit", fn) form.addEventListener("submit", validateData);
change Fires when an element's value changes (for inputs, only upon loss of focus; for select, immediately). element.addEventListener("change", fn) selectField.addEventListener("change", updatePrice);
input Fires IMMEDIATELY with every character typed into a field (perfect for real-time validation). element.addEventListener("input", fn) passwordField.addEventListener("input", checkPasswordStrength);
focus / blur focus when a field gains focus (clicked into); blur when a field loses focus. element.addEventListener("focus", fn) inputField.addEventListener("focus", highlightGreen);
invalid Fires when an element does not satisfy HTML5 validation constraints upon form submission. element.addEventListener("invalid", fn) emailField.addEventListener("invalid", showError);
→ Window / Document Events
DOMContentLoaded Fires on the document when the initial HTML is completely loaded and parsed (does not wait for images/styles). document.addEventListener("DOMContentLoaded", fn) document.addEventListener("DOMContentLoaded", initializeTutorial);
load Fires on the window when the complete page is FULLY loaded (including images and CSS). window.addEventListener("load", fn) window.addEventListener("load", stopLoadingSpinner);
resize Fires on the window whenever the browser window size changes. window.addEventListener("resize", fn) window.addEventListener("resize", adjustDisplay);
scroll Fires when the document view or an element has been scrolled up/down/sideways. element.addEventListener("scroll", fn) window.addEventListener("scroll", updateScrollToTopBtn);
7. Collections and Lists
forEach() A method available on NodeList that allows easy traversal through all matched elements. nodelist.forEach(item => { ... }) btns.forEach(b => b.classList.add("style-class"));
Array.from() Converts a pseudo-array (HTMLCollection/NodeList) into a real array to use map/filter methods. Array.from(collection) const array = Array.from(document.children);
length Returns the number of elements/nodes inside a collection. collection.length console.log(rows.length);

Key Practical Scenarios in Practice

In real-world web development, you will constantly encounter three specific challenges. Below are advanced examples prepared to solve these problems using optimal DOM methods:

Scenario / Issue DOM Event Solution Action
1. Page reloading upon form submission
When clicking submit, the browser always reloads the entire page, which interrupts the user experience.
Using e.preventDefault() on the submit event, which allows data verification and background sending (AJAX). ▶ Code Example
2. Dynamically added elements do not react
If you append rows or buttons later using JavaScript, classic event listeners will not trigger on them.
Event Delegation. We attach the listener to a common parent, and capture the click via e.target. ▶ Code Example
3. Real-time (live) input field verification
The change event waits for a loss of focus, but users want feedback immediately.
Using the input event, which triggers on every single character typed (e.g., real-time password strength check). ▶ Code Example