Today, you'll gain the superpower to change any part of your webpage using JavaScript. We'll explore the Document Object Model (DOM), which is a map of your HTML page that JavaScript can read and modify.
The browser turns your HTML code into a tree-like structure called the DOM. Each HTML tag becomes a "node" or "element" in this tree. JavaScript can access this tree to find, change, add, or delete elements, making your pages fully dynamic and interactive.
JavaScript gives us special functions (called methods) to interact with the DOM. Here are the key ones for today's lesson:
innerHTML property to read or
change the HTML content inside it.
appendChild to place your new element inside it.
In the editor on the right, you'll find three empty JavaScript functions. Your job is to fill in the missing code step by step. Each function controls what happens when you click the buttons. Test your code by clicking "Run Code" and then trying the buttons!
Follow the pattern: 1. Select the element with document.getElementById(). 2. Modify its properties like innerHTML or className. Don't forget the semicolons!
changeContent() function in the editor. Fill in the missing code:
const element = document.getElementById('dynamicContent');
element.innerHTML = '<strong>Content changed with JavaScript!</strong>';
element.className = 'alert alert-success';
addElement() function:
const container = document.getElementById('newElements');
const newDiv = document.createElement('div');
newDiv.className = 'alert alert-warning mt-2';
newDiv.innerHTML = '<strong>New element added!</strong>';
container.appendChild(newDiv);
const element = document.getElementById('dynamicContent');
element.innerHTML = 'Original content here';
element.className = 'alert alert-info';
document.getElementById('newElements').innerHTML = '';
Practice your new DOM manipulation skills by adding more buttons and functions. Can you make a button that changes the color of the heading? Or a button that adds an image to the page? In the next lesson, we'll use these skills to work with lists of data using arrays and loops.