Day 9: JavaScript DOM Manipulation
Overview
Today, we will learn how to manipulate the DOM (Document Object Model) using JavaScript. This allows us to dynamically update the content and structure of our web pages.
What is the DOM?
The DOM is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as a tree of nodes.
Accessing DOM Elements
To manipulate the DOM, we first need to access the elements we want to change. We can do this using methods like getElementById, getElementsByClassName, and querySelector.
// Accessing an element by ID
var element = document.getElementById("myElement");
// Accessing elements by class name
var elements = document.getElementsByClassName("myClass");
// Accessing an element using query selector
var element = document.querySelector(".myClass");
Changing Content
We can change the content of an element using the innerHTML or textContent properties.
// Changing the inner HTML
document.getElementById("myElement").innerHTML = "New Content";
// Changing the text content
document.getElementById("myElement").textContent = "New Text";
Changing Styles
We can change the style of an element using the style property.
// Changing the style
document.getElementById("myElement").style.color = "blue";
document.getElementById("myElement").style.backgroundColor = "yellow";
Creating and Removing Elements
We can create new elements and add them to the DOM, or remove existing elements from the DOM.
// Creating a new element
var newElement = document.createElement("div");
newElement.textContent = "Hello, World!";
document.body.appendChild(newElement);
// Removing an element
var element = document.getElementById("myElement");
element.parentNode.removeChild(element);
Practice Exercise
Try creating a simple JavaScript script that does the following:
- Creates a new paragraph element and adds it to the body.
- Changes the content of an existing element.
- Changes the style of an element.
// Your code here
// Creating a new paragraph element
var newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.body.appendChild(newParagraph);
// Changing the content of an existing element
document.getElementById("myElement").innerHTML = "Updated Content";
// Changing the style of an element
document.getElementById("myElement").style.color = "green";
Summary
In today's lesson, we covered JavaScript DOM manipulation. You learned how to access, change, and remove elements, as well as how to create new elements and change their styles. This knowledge will allow you to create dynamic and interactive web pages.