Class 11: JavaScript DOM Manipulation
In the previous classes, we learned the fundamentals of JavaScript, including variables, data types, control flow, and functions. Now, it's time to connect JavaScript with HTML to create dynamic and interactive web pages. This is where the Document Object Model (DOM) comes into play. It allows you to respond to user actions and dynamically update the user interface without requiring a full page reload.
Introduction to the Document Object Model (DOM)
The DOM is a programming interface for web documents. It represents the page structure as a tree of objects, where each node in the tree represents a part of the document (like an element, attribute, or text). JavaScript can interact with this DOM tree to change the content, structure, and style of a web page dynamically.
- The browser creates the DOM tree when it loads an HTML document.
- Each HTML element, attribute, and text within the document becomes a DOM node.
- JavaScript allows you to access and manipulate these nodes.
Selecting Elements
Before you can manipulate an HTML element with JavaScript, you need to select it from the DOM. There are several methods to do this:
document.getElementById()
Selects a single element by its unique
id
attribute. Returns null
if no
element with the specified ID is found.
<!-- HTML -->
<p id="myParagraph">This is a paragraph.</p>
// JavaScript
const paragraph = document.getElementById("myParagraph");
console.log(paragraph); // Outputs the <p> element
document.querySelector()
Selects the first element that matches a specified CSS selector
(e.g., tag name, class, ID, attribute). Returns
null
if no match is found.
<!-- HTML -->
<div class="container">First container</div>
<div class="container">Second container</div>
<a href="#" id="myLink">Click Me</a>
// JavaScript
const firstContainer = document.querySelector(".container");
console.log(firstContainer); // Outputs the first <div class="container">
const myLink = document.querySelector("#myLink");
console.log(myLink); // Outputs the <a id="myLink"> element
const anyParagraph = document.querySelector("p");
console.log(anyParagraph); // Outputs the first <p> element on the page
document.querySelectorAll()
Selects all elements that match a specified CSS selector.
Returns a NodeList
(which is similar to an array)
of all matching elements. Returns an empty
NodeList
if no matches are found.
<!-- HTML -->
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li>Item 3</li>
// JavaScript
const allItems = document.querySelectorAll(".item");
console.log(allItems); // Outputs a NodeList containing two <li class="item"> elements
// You can iterate over a NodeList using forEach or a for loop
allItems.forEach(item => {
console.log(item.textContent);
});
Modifying Elements
Once you have selected an element, you can modify its content, attributes, and styles.
Modifying Content (textContent
,
innerHTML
)
-
textContent
: Gets or sets the text content of a node and its descendants. It's safer for inserting pure text as it handles HTML escaping. -
innerHTML
: Gets or sets the HTML or XML markup contained within an element. Be cautious when usinginnerHTML
with user-provided content, as it can expose you to Cross-Site Scripting (XSS) vulnerabilities.
<!-- HTML -->
<h2 id="title">Original Title</h2>
<div id="contentDiv">This is <strong>some</strong> content.</div>
// JavaScript
const title = document.getElementById("title");
title.textContent = "New Title for the Page";
console.log(title.textContent);
const contentDiv = document.getElementById("contentDiv");
contentDiv.innerHTML = "Updated content with <em>emphasis</em>.";
console.log(contentDiv.innerHTML);
Modifying Attributes (setAttribute()
,
removeAttribute()
, getAttribute()
)
-
setAttribute(name, value)
: Sets the value of an attribute on the specified element. -
removeAttribute(name)
: Removes an attribute from the specified element. -
getAttribute(name)
: Returns the value of a specified attribute on the element.
<!-- HTML -->
<img id="myImage" src="placeholder.jpg" alt="A placeholder image">
<a id="myLink" href="old-page.html">Go to Old Page</a>
// JavaScript
const image = document.getElementById("myImage");
image.setAttribute("src", "new-image.jpg");
image.setAttribute("alt", "A new image description");
console.log(image.getAttribute("src"));
const link = document.getElementById("myLink");
link.setAttribute("href", "new-page.html");
link.textContent = "Go to New Page";
link.removeAttribute("id"); // Removes the id attribute
Modifying Styles (style
property,
classList
)
-
element.style.propertyName
: Directly manipulates inline styles. Property names are camelCased (e.g.,backgroundColor
instead ofbackground-color
). -
element.classList.add()
,element.classList.remove()
,element.classList.toggle()
: Manipulates CSS classes. This is generally preferred for managing styles as it keeps styling concerns in CSS stylesheets.
<!-- HTML -->
<div id="styledDiv" class="box">Style Me!</div>
<!-- CSS (in styles.css) -->
.highlight {
background-color: yellow;
border: 2px solid orange;
padding: 10px;
}
// JavaScript
const styledDiv = document.getElementById("styledDiv");
// Direct style manipulation (inline styles)
styledDiv.style.color = "blue";
styledDiv.style.fontSize = "20px";
styledDiv.style.border = "1px solid red";
// Using classList (preferred)
styledDiv.classList.add("highlight"); // Adds the 'highlight' class
styledDiv.classList.remove("box"); // Removes the 'box' class
styledDiv.classList.toggle("active"); // Adds 'active' if not present, removes if present
console.log(styledDiv.classList.contains("highlight"));
Creating and Appending New Elements
You can dynamically create new HTML elements and add them to the DOM.
<!-- HTML -->
<ul id="myList">
<li>Existing Item</li>
</ul>
<div id="container"></div>
// JavaScript
const myList = document.getElementById("myList");
// 1. Create a new element
const newItem = document.createElement("li");
// 2. Add content to the new element
newItem.textContent = "Dynamically Added Item";
newItem.style.color = "green";
// 3. Append the new element to an existing parent
myList.appendChild(newItem); // Adds newItem as the last child of myList
// Creating a new paragraph and adding it to a div
const container = document.getElementById("container");
const newParagraph = document.createElement("p");
newParagraph.innerHTML = "This paragraph was <strong>created by JS</strong>.";
container.appendChild(newParagraph);
// Adding multiple items with a loop
const colors = ["Red", "Green", "Blue"];
colors.forEach(color => {
const colorItem = document.createElement("li");
colorItem.textContent = color;
myList.appendChild(colorItem);
});
/* Expected HTML after JS execution:
<ul id="myList">
<li>Existing Item</li>
<li style="color: green;">Dynamically Added Item</li>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>
<div id="container">
<p>This paragraph was <strong>created by JS</strong>.</p>
</div>
*/