By the end of this lesson, you will understand the DOM and how JavaScript can read and change web pages effectively.
The DOM stands for Document Object Model. It creates a structure that represents the HTML of a web page. You can think of it as a map of the page. Just like you can read a map and find your way around, JavaScript can read the DOM and make changes to the web page. For example, when you click a button on a website, it might change text in a box. This happens because JavaScript is using the DOM to update the page. Therefore, it is crucial to understand the DOM for effective web development.
The structure of the DOM is hierarchical. It consists of nodes that represent various elements of the document. For example, an HTML document consists of elements like <html>, <head>, and <body>. Each of these elements can have child elements, creating a tree-like structure. In addition, this structure allows JavaScript to easily navigate and manipulate the document. Understanding the DOM structure helps you write better JavaScript code.
File: changeText.js
// Select the button and the text element
const button = document.querySelector('#changeTextButton');
const textElement = document.querySelector('#text');
// Add a click event to the button
button.addEventListener('click', function() {
textElement.textContent = 'Text has been changed!';
});
Expected Output:
Text has been changed!
In this code, we first select a button and a text element from the web page. We use document.querySelector to find these elements. Then, we add a click event to the button using addEventListener. When the button is clicked, the text content of textElement changes. This showcases how to effectively use the DOM with JavaScript to modify web page elements. Also, it illustrates the interaction between JavaScript and the web page structure.
Your task is to create a simple web page. Make a button that changes the background color of the page. This will help you see how JavaScript can interact with the DOM to change elements. First, set up your HTML structure. Then implement your JavaScript to achieve the desired outcome.
// Select the button
const button = document.querySelector('#colorButton');
// Add a click event to the button
button.addEventListener('click', function() {
document.body.style.backgroundColor = 'lightblue';
});
document.querySelector to select elements efficiently.click can trigger changes on a web page, which is essential to understand the DOM.For more information on how JavaScript works within web pages, check out the lesson on JavaScript basics.