1. Understanding the DOM
What is the DOM?
The Document Object Model (DOM) is a programming interface for web documents that represents the structure of a webpage as a tree of objects.Difference between HTML, CSSOM, and DOM
- HTML: The markup language defining the structure of a webpage.
- CSSOM: The CSS Object Model, representing the styles of a webpage.
- DOM: A structured representation of the document that allows JavaScript to manipulate elements.
DOM Tree Structure
The DOM represents an HTML document as a hierarchical tree with the following components:- Nodes: The fundamental building blocks (Elements, Text, Attributes, etc.).
- Elements: HTML elements such as
<div>,<p>,<button>, etc. - Attributes: Properties like
id,class,hrefthat define elements. - Text: The actual content inside an element.
2. Selecting Elements
document.getElementById("id")- Selects an element by its unique ID.document.getElementsByClassName("class")- Returns a collection of elements with the given class name.document.getElementsByTagName("tag")- Returns a collection of elements with the specified tag name.document.querySelector("selector")- Selects the first element that matches the CSS selector.document.querySelectorAll("selector")- Selects all elements that match the CSS selector.
3. Modifying the DOM
Changing Text Content
element.textContent- Sets or gets the text inside an element, ignoring HTML.element.innerText- Similar totextContent, but respects styling (e.g., hidden elements).element.innerHTML- Sets or gets HTML content inside an element.
Changing Attributes
element.setAttribute("attr", "value")- Sets an attribute value.element.getAttribute("attr")- Retrieves an attribute value.element.removeAttribute("attr")- Removes an attribute.
Modifying Styles
element.style.property = "value"- Changes a single inline style.element.classList.add("class")- Adds a class.element.classList.remove("class")- Removes a class.element.classList.toggle("class")- Toggles a class on and off.
4. Creating and Removing Elements
document.createElement("tag")- Creates a new element.document.createTextNode("text")- Creates a text node.parent.appendChild(child)- Appends a child element.parent.append(child1, child2, ...)- Appends multiple children.parent.removeChild(child)- Removes a child element (older method).element.remove()- Removes an element directly (modern approach).
5. Event Handling in the DOM
Adding Event Listeners
element.addEventListener("event", callback)- Attaches an event listener.element.onclick = function() { ... }- Sets an event listener (not recommended for multiple events).
Event Object
event.target- The element that triggered the event.event.preventDefault()- Prevents default behavior (e.g., stopping form submission).event.stopPropagation()- Prevents event bubbling.
Event Delegation
- Uses event bubbling to handle events efficiently on parent elements instead of individual children.
6. Traversing the DOM
Parent Elements
element.parentNode- Gets the parent node.element.parentElement- Gets the parent element.
Children Elements
element.childNodes- Returns all child nodes (including text and comments).element.children- Returns child elements only.element.firstChild/element.lastChild- Returns the first/last child node.
Siblings
element.previousSibling/element.nextSibling- Gets the previous/next sibling node.
7. Forms & Input Handling
Accessing Form Elements
document.forms["formName"]- Accesses a form.input.value- Retrieves or sets the value of an input.checkbox.checked- Checks if a checkbox is checked.
Handling User Input
element.oninput- Fires when input changes.element.onchange- Fires when input loses focus after change.element.onsubmit- Fires when a form is submitted.
Form Validation
element.setCustomValidity("message")- Sets a custom validation message.element.checkValidity()- Checks if input is valid.
8. Advanced DOM Manipulation
Cloning Elements
element.cloneNode(true/false)- Clones an element (truecopies children).
Template Elements
<template>is used to define reusable HTML snippets without rendering them.template.content.cloneNode(true)- Clones template content for insertion.
MutationObserver API
- Used to watch for DOM changes dynamically.
9. Performance Optimization in DOM Manipulation
Minimizing Repaints & Reflows
- Reduce direct DOM manipulations and batch updates.
Using Document Fragments
document.createDocumentFragment()- Reduces reflows by manipulating elements off-screen.
Debouncing & Throttling Event Handlers
- Helps optimize frequent event calls like scrolling and resizing.
10. Asynchronous DOM Updates
Using
requestAnimationFrame()- Efficiently schedules UI updates for smooth animations.
Using
setTimeout()andsetInterval()- Handles delayed execution and repeated UI updates.
Intersection Observer API
- Detects when elements appear in the viewport (useful for lazy loading images).
11. Working with Browser APIs
LocalStorage, SessionStorage, and Cookies
localStorage.setItem("key", "value")- Stores data permanently.sessionStorage.setItem("key", "value")- Stores data for the session.document.cookie- Handles cookies.
Fetch API and Dynamic Content Insertion
fetch(url).then(response => response.json()).then(data => console.log(data))- Fetches and processes data dynamically.
Web Components and Shadow DOM
- Enables reusable custom elements with encapsulated styles and logic.