JavaScript Fundamentals
DOM Manipulation
DOM Manipulation
Section titled “DOM Manipulation”The DOM (Document Object Model) allows JavaScript to interact with HTML elements.
Selecting Elements
Section titled “Selecting Elements”// By IDconst element = document.getElementById("myId");
// By classconst elements = document.getElementsByClassName("myClass");
// By tagconst divs = document.getElementsByTagName("div");
// CSS selectors (recommended)const one = document.querySelector(".myClass");const all = document.querySelectorAll(".myClass");Modifying Elements
Section titled “Modifying Elements”Content
Section titled “Content”const el = document.querySelector("#myDiv");
el.textContent = "Plain text";el.innerHTML = "<strong>HTML content</strong>";Attributes
Section titled “Attributes”el.setAttribute("data-id", "123");el.getAttribute("data-id");el.removeAttribute("data-id");
// Direct property accessel.id = "newId";el.className = "newClass";Styles
Section titled “Styles”el.style.color = "red";el.style.backgroundColor = "blue";el.style.display = "none";
// Multiple stylesObject.assign(el.style, { color: "red", fontSize: "16px"});Classes
Section titled “Classes”el.classList.add("active");el.classList.remove("active");el.classList.toggle("active");el.classList.contains("active");Creating Elements
Section titled “Creating Elements”const div = document.createElement("div");div.textContent = "Hello";div.className = "greeting";
document.body.appendChild(div);
// Insert at specific positionparent.insertBefore(newElement, referenceElement);
// Remove elementelement.remove();Traversing the DOM
Section titled “Traversing the DOM”const el = document.querySelector("#myDiv");
el.parentElement; // Parentel.children; // Child elementsel.firstElementChild; // First childel.lastElementChild; // Last childel.nextElementSibling; // Next siblingel.previousElementSibling; // Previous sibling