Here’s a cheat sheet for DOM (Document Object Model) manipulation using JavaScript:
DOM Basics
Accessing Elements:
// By ID
const elementById = document.getElementById("elementId");
// By Class
const elementsByClass = document.getElementsByClassName("className");
// By Tag
const elementsByTag = document.getElementsByTagName("tagName");
// By Selector
const elementBySelector = document.querySelector("selector");
const elementsBySelectorAll = document.querySelectorAll("selector");
Manipulating Content:
// Get/Set Text Content
element.textContent = "New text content";
const textContent = element.textContent;
// Get/Set HTML Content
element.innerHTML = "<p>New HTML content</p>";
const htmlContent = element.innerHTML;
Attributes:
// Get/Set Attribute
const value = element.getAttribute("attributeName");
element.setAttribute("attributeName", "newValue");
// Check if Attribute Exists
const hasAttribute = element.hasAttribute("attributeName");
// Remove Attribute
element.removeAttribute("attributeName");
DOM Traversal
Parent, Child, and Siblings:
// Parent Node
const parent = element.parentNode;
// Children Nodes
const children = element.childNodes;
// First and Last Child
const firstChild = element.firstChild;
const lastChild = element.lastChild;
// Siblings
const previousSibling = element.previousSibling;
const nextSibling = element.nextSibling;
Creating and Appending Elements:
// Create Element
const newElement = document.createElement("tagName");
// Append Element
parent.appendChild(newElement);
// Insert Before
parent.insertBefore(newElement, existingElement);
Event Handling
Event Listeners:
element.addEventListener("click", function() {
// Handle the click event
});
// Remove Event Listener
element.removeEventListener("click", eventHandler);
Style Manipulation
CSS Classes:
// Add Class
element.classList.add("newClass");
// Remove Class
element.classList.remove("existingClass");
// Toggle Class
element.classList.toggle("toggleClass");
Style Properties:
// Get/Set Style Property
element.style.propertyName = "value";
const styleValue = element.style.propertyName;
Window and Document
Window Properties:
// Window Size
const windowHeight = window.innerHeight;
const windowWidth = window.innerWidth;
// Scroll Position
const scrollTop = window.scrollY;
const scrollLeft = window.scrollX;
Document Properties:
// Document Title
const documentTitle = document.title;
// Document URL
const documentURL = document.URL;
// Body Element
const bodyElement = document.body;
Common Methods
setTimeout and setInterval:
// setTimeout
setTimeout(function() {
// Code to execute after a delay
}, 1000); // 1000 milliseconds
// setInterval
const intervalId = setInterval(function() {
// Code to execute at regular intervals
}, 2000); // 2000 milliseconds
// Clear Interval
clearInterval(intervalId);
These examples cover some basic DOM manipulation using JavaScript. For more details and advanced features, refer to the MDN Web Docs.