Hello, World DOMination: Element Selection and Placement

Introduction

The objective of this lesson is to familiarize yourself with the usage and inner workings of the DOM (Document Object Model) API. By the end of this lesson, you will be able to:

What is the DOM?

The Document Object Model (DOM) is an object-oriented representation of an HTML document or webpage. It represents the document as objects, or nodes, which developers can manipulate using JavaScript.

The DOM is structured as a tree, with parent nodes representing higher branches and child nodes representing lower branches. This hierarchy allows for precise navigation and manipulation of the document.

Referencing the DOM

Accessing elements in the DOM is a fundamental skill for any frontend developer. Let’s explore two common methods for referencing elements:

Using document.getElementById()

To reference a single element by its id:


HTML:
<div> id="catch-me-if-you-can">HI!</div>

JavaScript:
const divOfInterest = document.getElementById("catch-me-if-you-can");
            

Using document.querySelectorAll()

To reference multiple elements by a class name or selector:


HTML:
<span class="cloudy"></span>
<span class="cloudy"></span>
...

JavaScript:
const cloudySpans = document.querySelectorAll("span.cloudy");
            

querySelectorAll returns a static NodeList, which can be iterated over using forEach():


cloudySpans.forEach(span => {
  console.log("Cloudy!");
});
            

Creating New DOM Elements

You can dynamically create elements and add them to the DOM. For example:

HTML Structure


        <!DOCTYPE html>
        <html>
            <head>
            <title>DOM Example</title>
            <script type="text/javascript" src="example.js"></script>
            </head>
            <body></body>
        </html>
            

JavaScript to Create and Add Elements


const addElement = () => {
  const newElement = document.createElement("h1"); // Create a new h1
  newElement.setAttribute("id", "sleeping-giant"); // Set its ID
  const newContent = document.createTextNode("Jell-O, Burled!"); // Add content
  newElement.appendChild(newContent); // Attach content to the element
  document.body.appendChild(newElement); // Append the element to the DOM
};

window.onload = addElement; // Run the function when the page loads
            

When you load the page, you’ll see the new h1 element on the screen.

What You Learned

In this lesson, you learned:

Mastering these techniques will allow you to build dynamic, interactive web pages with ease.