DEV Community

Cover image for Exploring JavaScript's Document Object Model (DOM).
Folacodes
Folacodes

Posted on

Exploring JavaScript's Document Object Model (DOM).

In my quest to deep dive into the building blocks of Frontend Engineering, I recently took a course on Frontend Masters titled Vanilla JavaScript: You might not need a Framework by Maximiliano Firtman on Frontend Masters. It's a cool course that you should totally check out.

This article is an attempt to share what I learned from the course and further deepen my understanding of Vanilla JS. One of the key concepts the course explores in depth is the Document Object Model (DOM), which forms the foundation of how JavaScript interacts with web pages.

Having a good understanding of how the DOM works under the hood as a Frontend Engineer is key because it would help make better, performance-conscious decisions when working with JavaScript, whether using vanilla JS or frameworks like React.

Let me share the DOM definitions that resonated most with me from the course.

  • The DOM is a memory representation of your HTML.

  • The DOM is a structure browsers create in memory when rendering pages.

  • The DOM is a bridge that connects web pages to JavaScript through document structure.

Now, to interact with the DOM, the browser provides Application Programming Interfaces(API) called the DOM API. The DOM API is a browser API exposed to developers to manipulate the DOM from a scripting language like JavaScript.

In essence, The DOM is a structure in memory while the DOM API provides/ exposes ways in which that structure can be changed.This API is available on many Objects like:

  1. Window global Object
  2. Document Object (which represents the current DOM)
  3. Every HTML Element in a web app

Working with the DOM

As earlier mentioned, the DOM APIs allow us to interact/manipulate the DOM, some of the ways by which we can do that include:

  1. Selecting elements from the DOM: We can select elements from the DOM using several methods:
  • By ID: To retrieve an HTML element by its id attribute in JavaScript, the document.getElementById() method (what functions in an objects are called). This method returns a single HTML Element (or null if no element is found). Because ids are unique, it would only return the first element it encounters with that id.
<!-- HTML -->
<div id="header">Welcome to my site</div>
<p id="intro">This is the introduction paragraph</p>
Enter fullscreen mode Exit fullscreen mode
// JavaScript
const headerElement = document.getElementById('header');
const introElement = document.getElementById('intro');

console.log(headerElement.textContent); 
// "Welcome to my site"
console.log(introElement.textContent); 
// "This is the introduction paragraph"

// If ID doesn't exist
const nonExistent = document.getElementById('notFound');
console.log(nonExistent); 
// null
Enter fullscreen mode Exit fullscreen mode
  • By Classname: We can also get an HTML element by its classname, using the document.getElementsByClassName() method. This method returns a Live HTML Collection(HTML Collection) - a live collection that automatically updates when the DOM changes.
<!-- HTML -->
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<p class="card">Card 3</p>
Enter fullscreen mode Exit fullscreen mode
// JavaScript
const cardElements = document.getElementsByClassName('card');
console.log(cardElements.length); // 3

// Access individual elements
console.log(cardElements[0].textContent); // "Card 1"
console.log(cardElements[1].textContent); // "Card 2"

// Live collection - updates automatically
const newCard = document.createElement('div');
newCard.className = 'card';
newCard.textContent = 'Card 4';
document.body.appendChild(newCard);

console.log(cardElements.length); // Now 4 (automatically updated!)
Enter fullscreen mode Exit fullscreen mode

Note - Live HTMLCollections don't have all the modern Array interface such as filter, map, reduce or forEach.
Modern array functions can be added to a live HTMLCollection by creating an Array from it using the Array.from() method.

  • By Name: Elements can also be retrieved using their name attribute with the document.getElementsByName() method. This method returns a Static Element Collection (A NodeList). Since the name attribute is not required to be unique (unlike id), this method typically returns a collection of elements, even if there's only one element with that name.
<form>
  <input type="radio" name="gender" value="male"> Male
  <input type="radio" name="gender" value="female"> Female
  <input type="radio" name="gender" value="other"> Other
</form>
Enter fullscreen mode Exit fullscreen mode
// JavaScript
const genderInputs = document.getElementsByName('gender');
console.log(genderInputs.length); // 3

// Loop through the collection
genderInputs.forEach((input, index) => {
    console.log(`Input ${index + 1}: ${input.value}`);
});
// Output:
// Input 1: male
// Input 2: female  
// Input 3: other

// Check which one is selected
const selectedGender = Array.from(genderInputs).find(input => input.checked);
console.log(selectedGender?.value); // Value of selected radio button
Enter fullscreen mode Exit fullscreen mode
  • By CSS Selectors: Elements can also be gotten using CSS selectors through the document.querySelector(selector) method. This method returns the first Element within the document that matches the specified CSS selector. If no matching element is found, it returns null.
<!-- HTML -->
<div class="container">
  <h1 id="main-title">Welcome</h1>
  <p class="intro">First paragraph</p>
  <p class="intro">Second paragraph</p>
  <button type="submit" data-action="save">Save</button>
  <input type="email" placeholder="Enter email">
</div>
Enter fullscreen mode Exit fullscreen mode
// Select by ID (same as getElementById)
const title = document.querySelector('#main-title');
console.log(title.textContent); // "Welcome"

// Select by class (returns first matching element)
const firstIntro = document.querySelector('.intro');
console.log(firstIntro.textContent); // "First paragraph"

// Select by element tag
const firstParagraph = document.querySelector('p');
console.log(firstParagraph.textContent); // "First paragraph"

// Select by attribute
const submitButton = document.querySelector('[type="submit"]');
const saveButton = document.querySelector('[data-action="save"]');
console.log(submitButton.textContent); // "Save"

// Select by complex CSS selector
const emailInput = document.querySelector('input[type="email"]');
console.log(emailInput.placeholder); // "Enter email"

// Descendant selector
const containerTitle = document.querySelector('.container h1');
console.log(containerTitle.textContent); // "Welcome"

// If selector doesn't match anything
const nonExistent = document.querySelector('.not-found');
console.log(nonExistent); // null
Enter fullscreen mode Exit fullscreen mode

Conclusion
Understanding how to select DOM elements is the foundation of JavaScript web development. Whether you're using getElementById() for unique elements, getElementsByClassName() for collections, getElementsByName() for form elements, or querySelector() for flexible CSS-based selection, mastering these methods gives you the tools to interact with any web page.

In the next part of this series, we'll explore how to manipulate these selected elements - modifying their content, attributes, styles, and structure. We'll also dive into creating new elements and handling events to build truly interactive web applications.
The DOM might seem complex at first, but once you understand these selection fundamentals, you're well on your way to becoming proficient in vanilla JavaScript.

And remember, this knowledge directly transfers to framework work too - React, Vue, and others are all built on these same DOM principles under the hood.

Stay tuned for Part 2 where we'd explore more on DOM manipulation.

You can always reach out on Twitter

Top comments (4)

Collapse
 
olabayobalogun profile image
OLABAYO BALOGUN

Amazing

Collapse
 
folacodes profile image
Folacodes

Thank you

Collapse
 
omogbai profile image
Omogbai Atakpu

Great article. Can't wait for Part 2.

Collapse
 
folacodes profile image
Folacodes

Thank you. Definitely on its way