Lesson 9: JavaScript DOM Manipulation
Lesson Notes
The **Document Object Model (DOM)** represents the structure of an HTML document as a tree of objects. JavaScript allows us to dynamically select, modify, and create elements in the DOM.
1. Selecting Elements
JavaScript provides various methods to select elements from the DOM:
document.getElementById("id")
→ Selects an element by **ID**.document.getElementsByClassName("class")
→ Selects elements by **class name**.document.getElementsByTagName("tag")
→ Selects elements by **tag name**.document.querySelector("selector")
→ Selects the **first** element matching a CSS selector.document.querySelectorAll("selector")
→ Selects **all** elements matching a CSS selector.
2. Modifying Elements
Once an element is selected, it can be modified using JavaScript:
element.innerHTML = "New Content";
→ Changes the element’s **HTML content**.element.textContent = "New Text";
→ Changes the **text content** inside an element.element.style.color = "red";
→ Modifies the **CSS style** of an element.element.setAttribute("class", "new-class");
→ Sets an **attribute** of an element.
3. Creating and Removing Elements
JavaScript allows adding and removing elements dynamically:
document.createElement("tag")
→ Creates a new **HTML element**.parent.appendChild(child)
→ Adds a new **child element** to a parent.parent.removeChild(child)
→ Removes an **element** from the DOM.
Example: Selecting, Modifying, and Creating Elements
// Selecting an element by ID
let element = document.getElementById("exampleText");
// Changing text content
element.textContent = "This text has been changed dynamically!";
// Modifying CSS style
element.style.color = "blue"; // Change text color
// Creating a new paragraph element
let newParagraph = document.createElement("p");
newParagraph.textContent = "This paragraph was added dynamically.";
// Appending the new paragraph to the body
document.body.appendChild(newParagraph);
let element = document.getElementById("exampleText");
// Changing text content
element.textContent = "This text has been changed dynamically!";
// Modifying CSS style
element.style.color = "blue"; // Change text color
// Creating a new paragraph element
let newParagraph = document.createElement("p");
newParagraph.textContent = "This paragraph was added dynamically.";
// Appending the new paragraph to the body
document.body.appendChild(newParagraph);
Explanation:
- getElementById: Selects an element by its **ID**.
- textContent: Updates the text inside an element.
- style.color: Changes the **text color**.
- createElement: Dynamically **creates a new paragraph**.
- appendChild: Adds the new element to the document.
These methods allow JavaScript to dynamically update web pages without reloading them.