← Back to Course Overview

Module 1: The DOM

In this module, you'll learn about the Document Object Model (DOM) and how to manipulate it using JavaScript. The DOM is a programming interface for web documents that represents the page as a structured tree of objects, enabling JavaScript to interact with and modify HTML and CSS dynamically.

Introduction to the DOM

Learn about what the DOM is and how it represents your HTML document as a tree of objects. The DOM is not part of JavaScript but a Web API used by JavaScript to interact with HTML documents, providing a structured representation where each element becomes a node in the tree.

Key Concepts

When a web page is loaded into a browser, the browser first looks for the HTML file. Next, the browser uses the HTML file as a blueprint or instructions on building the page. Finally, the browser parses these instructions and builds a model for the page's look and functionality using Javascript. This model is a Javascript Object containing every element in order on the page. This object is referred to as the DOM or Document Object Model.

The DOM is built as a data structure known as a 'Tree' because parent elements have nested children elements (or leaves). As with physical trees, we can follow tree branches to get to the exact leaf (or leaves) that we want to access. Each branch of our DOM tree can be its own tree.

When the DOM is built and the webpage is loaded, developers get access to it in the form of the global Javascript object document. document contains the entire hierarchy of the page, each element (or DOM node), and it also contains dozens of built in methods and properties.

Understanding the DOM Structure

Explore the hierarchical structure of the DOM and how elements are related to each other. You'll learn about parent-child relationships, sibling elements, and how the browser creates this tree structure from your HTML document.

DOM Tree Structure

The DOM represents your HTML as a tree structure, with each HTML element becoming a node in the tree. The document object is the root node, and all other elements are child nodes organized in a hierarchical structure. Understanding this structure is important for navigating and manipulating elements efficiently.

Key relationships in the DOM tree include:

  • Parent-child: Elements can contain other elements, creating a parent-child relationship
  • Siblings: Elements that share the same parent
  • Ancestors-descendants: Elements higher or lower in the hierarchy relative to a given element

DOM Selectors

Learn about different ways to select elements from the DOM using various methods like getElementById, getElementsByClassName, getElementsByTagName and how each returns different types of collections or individual elements.

Types of DOM Selectors

To manipulate elements on the DOM, we need to select them. There are many ways of doing this; for example, we can select the body and the head by asking for them (document.body, document.head). But, when we want to go deeper, that's where things get complicated. Thankfully, document has several built-in methods for accessing the exact element(s) we want.

getElement Methods

These are the original methods for selecting elements from the DOM. They each take a single string as the only argument, containing either the id or class you are looking for.

  • document.getElementsByTagName('p') - Returns an HTMLCollection containing all elements with the specified tag name
  • document.getElementById('idName') - Returns a single element with the specified ID
  • document.getElementsByClassName('className') - Returns an HTMLCollection containing all elements with the specified class

querySelector Methods

These are the newest element selection methods added to the DOM. These methods allow us to select element(s) based on CSS style selectors (remember . is class and # is id).

  • document.querySelector('.custom-style') - Returns the first element that matches the selector
  • document.querySelectorAll('queryString') - Returns all elements matching the query string as a NodeList

Selecting Nodes with querySelector

Master the use of querySelector to find specific elements in the DOM using CSS selector syntax. This powerful method allows you to select elements using the same selectors you use in CSS, making it versatile and intuitive.

Using querySelector

This method will search for and return the first element that matches the value passed into the method. Remember that the biggest change from the older DOM selection methods is that we now need to pass the proper CSS selector into the argument.

For example, to select an element with class "custom-style", you would use:

document.querySelector('.custom-style');

Note that we use the dot (.) to specify we're looking for a class. If we wanted to select an element by ID, we would use the pound/hash (#) symbol:

document.querySelector('#main-header');

You can also use more complex CSS selectors:

document.querySelector('nav a.active');

Selecting Node Lists with querySelectorAll

Learn how to select multiple elements using querySelectorAll and work with NodeLists. Unlike some other collection methods, querySelectorAll returns a static NodeList that won't automatically update when the DOM changes.

Working with querySelectorAll

This method will search for and return ALL elements matching the query string. This method returns these elements in an array-like object called a NodeList.

A NodeList is similar to an array but doesn't have all the same methods. It does support forEach, but not methods like map or reduce.

You can convert a NodeList to a true Array using:

const elements = document.querySelectorAll('.item');
const elementsArray = Array.from(elements);

Once converted to an array, you can use all array methods on the collection.

Iterating Over Node Lists

Explore different ways to iterate over NodeLists using forEach and other methods. You'll learn how to process collections of DOM elements to apply changes to multiple elements efficiently.

The Difference between HTMLCollection, NodeList, and Array

When we use getElementsByClassName() or querySelectorAll() we get back either an HTMLCollection or a NodeList respectively. We refer to these as 'array-like objects.' They both have numerical zero-based indices and the length property, but that is all they share with an Array. NodeList does take it one step further and has access to .forEach.

To iterate over a NodeList, you can use the forEach method:

const items = document.querySelectorAll('.item');
items.forEach(item => {
  item.classList.add('selected');
});

For HTMLCollections, you'll need to either convert to an array first or use a traditional for loop:

const items = document.getElementsByClassName('item');
for (let i = 0; i < items.length; i++) {
  items[i].classList.add('selected');
}

Setting Text Content

Learn how to modify text content of elements using textContent. This property allows you to set or get the text content of an element, replacing any existing content and removing all HTML tags.

Modifying Text Content

Once you've selected an element, one of the simplest ways to modify it is by changing its text content. The textContent property gives you access to all the text within an element and its descendants.

To get the text content of an element:

const text = document.querySelector('.message').textContent;

To set the text content of an element:

document.querySelector('.message').textContent = 'New message';

Note that using textContent will replace all child elements with the new text. If you want to preserve HTML formatting, you can use innerHTML instead, but be cautious with innerHTML as it can introduce security risks if used with user-provided content.

Building New Elements

Master the creation of new DOM elements using createElement and techniques for configuring them with attributes, content, and styles before adding them to the document.

Creating Elements Dynamically

The DOM allows us to create entirely new elements using the createElement method. These elements exist in memory but aren't part of the DOM until we add them.

Basic steps for creating a new element:

  1. Create the element using document.createElement('tagName')
  2. Configure the element by setting attributes, text content, and styles
  3. Append the element to the DOM

Example:

// Create a new paragraph
const paragraph = document.createElement('p');

// Add text content
paragraph.textContent = 'This is a new paragraph.';

// Add a class
paragraph.classList.add('info-text');

// Add an attribute
paragraph.setAttribute('data-id', '123');

// Set inline style
paragraph.style.color = 'blue';

Adding Elements to the DOM

Learn different methods to add elements to the DOM, including appendChild, prepend, and insertAdjacentElement. These methods allow you to precisely control where new elements are placed in the document structure.

DOM Insertion Methods

After creating an element, you need to add it to the DOM. There are several methods to do this, each with different placement options:

  • appendChild: Adds as the last child of the parent element
  • prepend: Adds as the first child of the parent element
  • insertBefore: Adds before a specified reference node
  • insertAdjacentElement: Provides precise control using position strings

Example using appendChild:

const paragraph = document.createElement('p');
paragraph.textContent = 'New paragraph';
document.querySelector('.container').appendChild(paragraph);

Example using insertAdjacentElement:

const paragraph = document.createElement('p');
paragraph.textContent = 'New paragraph';
const referenceElement = document.querySelector('.reference');

// Possible positions: 'beforebegin', 'afterbegin', 'beforeend', 'afterend'
referenceElement.insertAdjacentElement('afterend', paragraph);

Additional Resources