Dom Methods in JavaScript
?? DOM Methods in JavaScript
What Are DOM Methods?
DOM methods are built-in functions provided by the DOM API that let you manipulate or interact with HTML elements programmatically.
They allow you to select, create, add, remove, or modify elements dynamically.
Commonly Used DOM Methods
| Method | Description | Example |
|---|---|---|
document.getElementById(id) | Selects element by its ID | const elem = document.getElementById("header"); |
document.querySelector(selector) | Selects the first element matching CSS selector | const btn = document.querySelector(".btn"); |
document.querySelectorAll(selector) | Selects all elements matching selector (returns NodeList) | const items = document.querySelectorAll("li"); |
element.appendChild(node) | Adds a new child node to an element | parent.appendChild(child); |
element.remove() | Removes the element from the DOM | element.remove(); |
element.setAttribute(name, value) | Sets or updates an attribute | elem.setAttribute("class", "active"); |
element.getAttribute(name) | Gets the value of an attribute | let href = link.getAttribute("href"); |
element.classList.add(className) | Adds a CSS class | elem.classList.add("highlight"); |
element.classList.remove(className) | Removes a CSS class | elem.classList.remove("hidden"); |
document.createElement(tagName) | Creates a new HTML element | const div = document.createElement("div"); |
element.insertBefore(newNode, referenceNode) | Inserts newNode before referenceNode | parent.insertBefore(newElem, existingElem); |
element.replaceChild(newChild, oldChild) | Replaces oldChild with newChild | parent.replaceChild(newElem, oldElem); |
element.cloneNode(deep) | Creates a copy of the element (deep = true clones children) | const copy = elem.cloneNode(true); |
Example: Adding a New Paragraph
const newPara = document.createElement("p");newPara.textContent = "This is a new paragraph.";document.body.appendChild(newPara);Example: Removing an Element
const oldElem = document.getElementById("old");oldElem.remove();Example: Changing an Attribute
const img = document.querySelector("img");img.setAttribute("src", "new-image.jpg");Summary
DOM methods let you select, create, insert, remove, and modify HTML elements.
They are essential tools for dynamic web page manipulation.
Want me to show how to use these methods with event listeners or how to efficiently manipulate large DOM trees?