Unit 6 - Notes
CSE326
Unit 6: Javascript DOM
1. DOM Introduction
The Document Object Model (DOM) is a programming interface for web documents (HTML and XML). It represents the page so that programs can change the document structure, style, and content.
Key Concepts
- Tree Structure: The DOM views an HTML document as a tree of nodes. Every element, attribute, and piece of text in the HTML is a node.
- Object-Oriented: Elements in the DOM are objects. They have properties (values associated with the object) and methods (actions the object can perform).
- Platform Independent: It is a W3C (World Wide Web Consortium) standard, meaning it functions consistently across different browsers and platforms.
- Dynamic HTML: JavaScript uses the DOM to create dynamic HTML. It can add, delete, or modify elements on the fly without reloading the page.
The DOM Tree Visual:
Document
└── html
├── head
│ └── title ("My Page")
└── body
├── h1 ("Header")
└── a (href="link.html")
2. DOM Document
The document object is the entry point into the web page. It represents the web page itself. To access any element in an HTML page, you always start with accessing the document object.
Common Document Properties
document.title: Sets or returns the title of the document.document.URL: Returns the full URL of the HTML document.document.domain: Returns the domain name of the server that loaded the document.document.body: Returns the<body>element.document.head: Returns the<head>element.document.cookie: Returns all name/value pairs of cookies in the document.
Writing to the Document
While rarely used in modern application development, document.write() can be used to write directly to the output stream.
document.write("Hello World!");
// Warning: Using this after the page has loaded will overwrite the entire document.
3. DOM Methods (Selection)
DOM methods are actions you can perform on HTML elements. The most common methods involve selecting elements to manipulate them.
Traditional Selection Methods
getElementById(id): Returns the element that has the ID attribute with the specified value.
JAVASCRIPTconst header = document.getElementById("main-title");getElementsByClassName(name): Returns a HTMLCollection (array-like list) of all elements with a specific class name.
JAVASCRIPTconst items = document.getElementsByClassName("list-item"); // Accessing the first item: items[0]getElementsByTagName(name): Returns a HTMLCollection of all elements with a specific tag name.
JAVASCRIPTconst paragraphs = document.getElementsByTagName("p");
Modern Selection Methods (Recommended)
querySelector(selector): Returns the first element that matches a specified CSS selector.
JAVASCRIPTconst firstButton = document.querySelector(".btn-primary"); const container = document.querySelector("#container");querySelectorAll(selector): Returns a NodeList containing all elements that match the specified CSS selector.
JAVASCRIPTconst allButtons = document.querySelectorAll("button.active"); // Can be iterated using forEach allButtons.forEach(btn => console.log(btn));
4. DOM Elements
Once selected, DOM elements are objects that can be manipulated, traversed, created, or deleted.
Creating and Removing Elements
document.createElement(tagName): Creates a new element node.document.createTextNode(text): Creates a new text node.element.appendChild(node): Adds a node as the last child of a node.element.remove(): Removes the element from the DOM.element.removeChild(node): Removes a child node from an element.
Example: Adding a new item to a list
// 1. Create the element
const newItem = document.createElement("li");
// 2. Add content
newItem.textContent = "New List Item";
// 3. Select the parent
const list = document.getElementById("myList");
// 4. Append
list.appendChild(newItem);
DOM Traversal (Navigating the Tree)
element.parentNode: Returns the parent element.element.childNodes: Returns a collection of child nodes (includes whitespace/text nodes).element.children: Returns a collection of child elements (ignores text nodes).element.nextElementSibling: Returns the next sibling element.element.previousElementSibling: Returns the previous sibling element.
5. DOM HTML
The DOM allows JavaScript to change the content and attributes of HTML elements.
Changing Content
innerHTML: Gets or sets the HTML content (inner HTML) of an element. It parses string as HTML.
JAVASCRIPTdocument.getElementById("demo").innerHTML = "<strong>Bold Text</strong>";textContent: Gets or sets the text content of a node and its descendants. It does not parse HTML tags (safer against XSS attacks).
JAVASCRIPTdocument.getElementById("demo").textContent = "<strong>Bold Text</strong>"; // Result displays literal characters: <strong>Bold Text</strong>innerText: Similar totextContentbut respects CSS styling (e.g., won't return text hidden via CSS).
Changing Attributes
- Property Access: Most standard attributes are available as properties.
JAVASCRIPTconst img = document.getElementById("myImage"); img.src = "new-pic.jpg"; img.id = "newId"; getAttribute(name): Returns the value of the attribute.
JAVASCRIPTconst link = document.querySelector("a"); console.log(link.getAttribute("href"));setAttribute(name, value): Sets the value of an attribute.
JAVASCRIPTconst input = document.querySelector("input"); input.setAttribute("type", "password");removeAttribute(name): Removes an attribute completely.
6. DOM CSS
JavaScript can manipulate the style of HTML elements dynamically.
The style Property
Used to add inline styles to an element. CSS properties in JavaScript use camelCase instead of kebab-case (e.g., background-color becomes backgroundColor).
const box = document.getElementById("box");
// Syntax: element.style.property = value
box.style.backgroundColor = "blue";
box.style.fontSize = "20px";
box.style.display = "none"; // Hides the element
The classList Property (Best Practice)
Instead of managing individual styles, it is often better to toggle CSS classes defined in a stylesheet.
element.classList.add("class"): Adds a class.element.classList.remove("class"): Removes a class.element.classList.toggle("class"): Adds if missing, removes if present.element.classList.contains("class"): Returns true/false.
// CSS: .active { color: red; font-weight: bold; }
const btn = document.querySelector("button");
btn.classList.add("active");
7. DOM Events
Events are "things" that happen to HTML elements. JavaScript uses Event Listeners to react to these events.
Common Events
- Mouse:
click,dblclick,mouseover,mouseout,mousedown,mouseup. - Keyboard:
keydown,keyup,keypress. - Form:
submit,change,focus,blur. - Window:
load,resize,scroll.
Handling Events
Method 1: HTML Attribute (Not Recommended)
<button onclick="alert('Hello')">Click Me</button>
Method 2: DOM Property
Assigns a function to the event property. Limit: Only one function per event per element.
const btn = document.getElementById("myBtn");
btn.onclick = function() {
console.log("Button clicked");
};
Method 3: addEventListener() (Best Practice)
Allows adding multiple event handlers to a single element without overwriting existing ones.
- Syntax:
element.addEventListener(event, function, useCapture)
const btn = document.getElementById("myBtn");
function handleClick() {
alert("Clicked!");
}
// Note: Do not use "on" prefix (use "click", not "onclick")
btn.addEventListener("click", handleClick);
The Event Object
When an event occurs, the browser passes an event object to the handler function containing details about the event.
document.querySelector("a").addEventListener("click", function(event) {
// Prevent the default action (e.g., stop link from navigating)
event.preventDefault();
// Identify the element that was clicked
console.log("Target:", event.target);
// Mouse coordinates
console.log("X:", event.clientX, "Y:", event.clientY);
});
Event Bubbling vs. Capturing
- Bubbling (Default): The inner-most element's event is handled first and then propagates up to outer elements.
- Capturing: The outer-most element's event is handled first and then propagates down to inner elements.