DOM Manipulation Cheat Sheet
DOM Manipulation Cheat Sheet
Selecting Elements
document.getElementById(id)
Selects an element by its ID.
const element = document.getElementById("myId");
document.getElementsByClassName(className)
Selects all elements with the given class.
const elements = document.getElementsByClassName("myClass");
document.getElementsByTagName(tagName)
Selects all elements with the given tag name.
const elements = document.getElementsByTagName("div");
document.querySelector(selector)
Selects the first element that matches the CSS selector.
const element = document.querySelector(".myClass");
document.querySelectorAll(selector)
Selects all elements that match the CSS selector.
const elements = document.querySelectorAll("p");
Modifying Elements
element.innerHTML
Gets or sets the HTML content inside an element.
element.innerHTML = "<b>Hello</b>";
element.textContent
Gets or sets the text content inside an element.
element.textContent = "Hello";
element.style.property = value
Modifies an inline CSS property.
element.style.color = "red";
document.createTextNode(text)
Creates a new text node.
const textNode = document.createTextNode("Hello World");
element.appendChild(childNode)
Appends a child element to a parent.
parentElement.appendChild(newDiv);
Event Handling
element.addEventListener(event, function)
Adds an event listener to an element.
element.addEventListener("click", () => alert("Clicked!"));
event.preventDefault()
Prevents the default action of an event.
event.preventDefault();
event.stopPropagation()
Stops event bubbling up the DOM tree.
event.stopPropagation();
element.children
Selects all child elements.
const children = element.children;
element.firstElementChild
Selects the first child element.
const firstChild = element.firstElementChild;
Example Code
Example JavaScript
Demonstrating DOM manipulation.
// Selecting an element
const title = document.getElementById("main-title");
// Modifying content
title.textContent = "Welcome to JavaScript DOM!";
// Adding a class
title.classList.add("highlight");