DOM Basics
advancedPart of JavaScript in the Browser
Theory
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page as a tree of nodes, where each node corresponds to an element, attribute, or text content. JavaScript can access and modify the DOM to create dynamic, interactive web pages.
The DOM hierarchy starts with the window object, which represents the browser window. The document object is a property of window and represents the entire HTML document. All DOM manipulation begins with the document object.
Selecting elements is the first step in DOM manipulation:
document.getElementById("id")— selects a single element by itsidattributedocument.querySelector("selector")— selects the first element matching a CSS selectordocument.querySelectorAll("selector")— returns a NodeList of all matching elements
Traversing the DOM moves between nodes:
element.parentElement— parent elementelement.children— HTMLCollection of child elementselement.nextElementSibling— next sibling elementelement.previousElementSibling— previous sibling element
Manipulating content and attributes:
textContent— gets/sets the text content of an element (ignores HTML tags)innerHTML— gets/sets the HTML content (parses HTML tags)getAttribute()/setAttribute()— for working with element attributesclassList— add, remove, toggle, and check CSS classes
Creating and removing elements:
document.createElement("tag")— creates a new elementparent.appendChild(child)— adds child to the end of parentparent.insertBefore(newChild, referenceChild)— inserts before a referenceelement.remove()— removes the elementparent.removeChild(child)— removes a child element
Event listeners make pages interactive:
element.addEventListener("event", handler)— attaches an event handler- Common events:
click,mouseover,mouseout,keydown,keyup,submit,load - The event object provides details about the event (
event.target,event.type,event.key)
Event delegation attaches a single listener to a parent element to handle events from multiple children, using event bubbling.
Practical Examples
Exercises
Toggle Dark Mode
Create HTML with a button and a div. When the button is clicked, toggle a 'dark-mode' class on the div. The dark mode class should change the background to black and text to white.
Starter Code:
<button id='toggleBtn'>Toggle Dark Mode</button>\n<div id='content'>Hello, World!</div>Expected Output:
Clicking the button toggles dark mode styling on the div.Dynamic List Generator
Create an input field and a button. When the user types text and clicks the button, add the text as a new list item (<li>) to an unordered list. Clear the input after adding.
Starter Code:
<input type='text' id='itemInput' placeholder='Enter item'>\n<button id='addBtn'>Add</button>\n<ul id='itemList'></ul>Expected Output:
Typing 'Apples' and clicking adds <li>Apples</li> to the list.Hover Card Preview
Create an image gallery with thumbnails. When the user hovers over a thumbnail, display a larger preview of the image in a separate div. When the mouse leaves, hide the preview.
Starter Code:
<div class='gallery'>\n <img src='thumb1.jpg' class='thumb' data-full='full1.jpg'>\n <img src='thumb2.jpg' class='thumb' data-full='full2.jpg'>\n</div>\n<div id='preview' style='display:none;'></div>Expected Output:
Hovering over a thumbnail shows the full-size image preview.Mini Quiz
Mini Quiz
Mini Project
Mini Project: Interactive To-Do List
Build a fully interactive to-do list application using DOM manipulation. Users can add, complete, and delete tasks.
Requirements:
Bonus Challenge
Add a 'Clear All Completed' button and localStorage persistence.