JavaScript Fundamentals 05: The Document Object Model

The DOM is a programming interface provided by browsers that represents the contents of a web page as a tree structure of objects. Each element on the page is represented as a node in the DOM tree, allowing scripts to read and manipulate the page's content, structure, and styles.

JavaScript Fundamentals 05:  The Document Object Model

Understanding the DOM is crucial for interacting with and manipulating web pages dynamically.

Watch the Video

What is the DOM?

The DOM is a programming interface provided by browsers that represents the contents of a web page as a tree structure of objects. Each element on the page is represented as a node in the DOM tree, allowing scripts to read and manipulate the page's content, structure, and styles.

Why is the DOM Important?

The DOM is what makes web pages interactive. Without it, web pages would be static, displaying content without the ability to respond to user actions. With the DOM, you can:

  • Dynamically change the contents of a webpage without reloading it.
  • Respond to user actions, like clicks and keystrokes.
  • Create, modify, and delete elements in the page to update the user interface.

Accessing Elements

A fundamental part of working with the DOM is accessing elements within the document. You can access elements using methods like getElementById(), getElementsByClassName(), and querySelector().

Example: Accessing an Element by ID

First, let's look at a piece of HTML code that we'll interact with using JavaScript:

<!DOCTYPE html>
    <title>Document Object Model (DOM) Exploration</title>
    <h1 id="page-title">Hello, SkillSprints!</h1>
    <button id="my-button">Click Me!</button>

In this HTML snippet, we have an <h1> element with an ID of page-title. This ID uniquely identifies the element within the document, making it accessible via JavaScript using the DOM.

Now, let's use JavaScript to access and modify this element:

let titleElement = document.getElementById('page-title');

This JavaScript code snippet uses document.getElementById('page-title') to access the <h1> element. The textContent property of titleElement (which represents the <h1> element) is then logged to the console, displaying the text "Hello, SkillSprints!".

By combining this HTML and JavaScript, we demonstrate a fundamental interaction with the DOM: accessing an element by its ID and then manipulating or querying its properties. This is a stepping stone to more dynamic interactions with web pages, allowing developers to create engaging, responsive content based on user input or other events.

Modifying the Document

Once you have access to an element, you can modify its properties to change how it appears and behaves on the page.

Example: Changing Text and Style

titleElement.textContent = 'Welcome to SkillSprints!'; = 'blue';

Here, we change the text content of the titleElement and set its color to blue.

Creating and Removing Elements

The DOM also allows you to dynamically create new elements and add them to the page or remove existing elements.

Example: Creating a New Element

To understand how we can dynamically add new elements to a webpage with JavaScript, let's start with a basic HTML structure:

<!DOCTYPE html>
    <title>DOM Manipulation</title>
    <div id="message-container">
    <button id="add-message">Add a New Message</button>

this HTML snippet, we have a <div> element with an ID of message-container, which will serve as the container for our new elements. There's also a button with an ID of add-message that users can click to add a new message.

Now, let's use JavaScript to add a new paragraph element inside the message-container when the button is clicked:

document.getElementById('add-message').addEventListener('click', function() {
    let newMessage = document.createElement('p');
    newMessage.textContent = 'This is a new message!';

This JavaScript code does the following:

  • Listens for a click event on the button with id="add-message".
  • Creates a new <p> element and sets its text content to "This is a new message!".
  • Appends the newly created <p> element to the message-container <div>.

Understanding the Process

  1. Event Listening: The addEventListener method listens for a click event on our "Add a New Message" button. This is how we capture user interaction to trigger a response.
  2. Creating an Element: The document.createElement('p') method creates a new paragraph element. This element exists in memory but is not yet visible on the page.
  3. Setting Content: We assign text to our new paragraph using the textContent property. This text is what will be displayed in the paragraph element.
  4. Appending to the DOM: Finally, by using appendChild, we insert our new paragraph into the message-container div. This action makes our paragraph visible on the webpage, inside the specified container.

Removing Elements

First, we'll set up a basic HTML page with a list of items and a button next to each item to remove it from the list:

<!DOCTYPE html>
    <title>Remove Elements Example</title>
    <ul id="item-list">
        <li>Item 1 <button class="remove-button">Remove</button></li>
        <li>Item 2 <button class="remove-button">Remove</button></li>
        <li>Item 3 <button class="remove-button">Remove</button></li>

    <script src="script.js"></script>

JavaScript for Removing an Element

Next, we'll add JavaScript to handle the click event on each "Remove" button, removing the corresponding list item from the page.

Create a file named script.js and include the following JavaScript code:

document.addEventListener('DOMContentLoaded', function() {
    const buttons = document.querySelectorAll('.remove-button');

    buttons.forEach(button => {
        button.addEventListener('click', function() {
            const li = this.parentNode;

Understanding the JavaScript Code

  • The DOMContentLoaded event ensures our JavaScript runs after the HTML document has been fully loaded.
  • We use document.querySelectorAll('.remove-button') to select all remove buttons on the page.
  • For each button, we add an event listener that listens for the click event.
  • When a button is clicked, we identify the parent list item (<li>) of the clicked button using this.parentNode.
  • We then remove the list item from its parent (<ul>) using parentNode.removeChild(li).

What This Example Demonstrates

This simple example shows how to dynamically remove elements from the DOM, a common requirement in interactive web applications. By understanding how to select elements, listen to user events, and manipulate the DOM, you can create more dynamic and responsive user interfaces.

Event Listeners

First, we'll define a simple HTML structure with a paragraph and a button. The button, when clicked, will change the text content of the paragraph.

<!DOCTYPE html>
    <title>Event Listener Example</title>
    <p id="message">Click the button to change this text.</p>
    <button id="change-text-btn">Change Text</button>

    <script src="script.js"></script>

In this HTML, we have:

  • A paragraph (<p>) element with an ID of message, which contains some default text.
  • A button (<button>) element with an ID of change-text-btn, which users can click to trigger an action.

JavaScript: Adding an Event Listener

Now, let's write the JavaScript code that adds an event listener to the button. When the button is clicked, the text of the paragraph changes. This JavaScript code should be placed in a file named script.js referenced at the bottom of the body in your HTML file.

document.addEventListener('DOMContentLoaded', function() {
    const changeTextButton = document.getElementById('change-text-btn');
    const messageParagraph = document.getElementById('message');

    changeTextButton.addEventListener('click', function() {
        messageParagraph.textContent = 'The text has been changed!';

Understanding the JavaScript Code

  • document.addEventListener('DOMContentLoaded', ...): This ensures our JavaScript code runs after the entire HTML document has been loaded, so all elements are accessible.
  • document.getElementById('change-text-btn'): This selects the button element based on its ID.
  • changeTextButton.addEventListener('click', ...): We attach an event listener to the button for the click event. This means the specified function will run when the button is clicked.
  • Inside the event listener function, we change the textContent of the messageParagraph to "The text has been changed!". This demonstrates dynamically modifying the DOM in response to user interaction.

What This Example Demonstrates

This example illustrates the basics of responding to user actions with JavaScript by using event listeners. Event listeners are crucial for creating interactive web pages that respond to user inputs, such as clicks, typing, or mouse movements. By manipulating the DOM based on these events, you can build rich, dynamic web experiences.

Try It Yourself: Interactive DOM Manipulation

Now that you've seen how to interact with the DOM using JavaScript, it's time to put your knowledge into practice. Here are a few exercises designed to reinforce the concepts you've learned:

Exercise 1: Update Page Content

  1. Objective: Dynamically update the content of a webpage.
  2. Task: Add an input field and a button to your HTML document. When the button is clicked, update a paragraph element with the text from the input field.
  3. Hint: Use getElementById to access the input and paragraph elements, and addEventListener to listen for the button click.

Exercise 2: Add New List Items

  1. Objective: Practice adding new elements to the DOM.
  2. Task: Create an unordered list (<ul>) and a button in your HTML document. Each time the button is clicked, add a new list item (<li>) to the list with some predefined text.
  3. Hint: Use createElement to create the new list item, and appendChild to add it to the list.

Exercise 3: Remove Elements on Click

  1. Objective: Learn to remove elements from the DOM.
  2. Task: Start with a list of several items, each with a "Remove" button next to it. When a button is clicked, remove the corresponding list item from the page.
  3. Hint: Attach an event listener to each "Remove" button, and use removeChild or remove to remove the clicked item's parent list item.

Exercise 4: Toggle Element Visibility

  1. Objective: Use event listeners to toggle the visibility of an element.
  2. Task: Include a paragraph of text and a button labeled "Toggle Visibility" in your HTML. When the button is clicked, toggle whether the paragraph is visible or hidden.
  3. Hint: Toggle a CSS class that sets display: none; on the paragraph using classList.toggle.

HTML Template to Get Started

Here's a basic HTML template to help you get started with the exercises:

<!DOCTYPE html>
    <title>DOM Manipulation Exercises</title>
    <input id="textInput" type="text" placeholder="Enter some text">
    <button id="updateTextBtn">Update Text</button>
    <p id="dynamicText">This text will change.</p>
    <ul id="itemList">
        <li>Sample Item <button class="remove-btn">Remove</button></li>
        <!-- Add items here -->
    <button id="addItemBtn">Add Item</button>
    <p id="toggleParagraph">Toggle my visibility!</p>
    <button id="toggleVisibilityBtn">Toggle Visibility</button>

    <script src="script.js"></script>

Final Thought

Congratulations on completing this deep dive into the Document Object Model (DOM)! By now, you've traversed the essential concepts that make the web interactive and dynamic. You've learned how the DOM acts as a bridge between your HTML documents and JavaScript, enabling you to create, modify, and interact with web pages in real-time.

Starting with understanding what the DOM is and its importance, you've explored how to access and manipulate elements, dynamically create and remove elements, and respond to user actions with event listeners. Each of these steps has equipped you with the skills to enhance user experiences on the web.

The exercises you've tackled are your first steps toward mastering DOM manipulation—a core skill in web development. Through your hard work and practice, you're now able to bring static web pages to life, making them responsive and interactive.