JavaScript Fundamentals: Master the DOM! (Part 1)

Timothy Robards
Mar 5 · 8 min read

The Document Object Model, or the “DOM”, defines the logical structure of HTML documents & essentially acts as an interface to web pages. Through the use of programming languages such as JavaScript, we can access the DOM to manipulate websites and make them interactive.

In this article we’re going to be working with the document object, taking a look at the DOM tree and nodes, and we’ll learn all about how to access and work with elements. Let’s get started!

This article is part of a series I’m writing on learning the JavaScript fundamentals. Be sure to follow me if you’d like to keep track!

What is the DOM?

At its core a website must consist of an HTML document, an index.html. Using a browser we view the website, which renders from our HTML file/s and any CSS files which add style and layout rules.

The browser also creates a representation of this document known as the Document Object Model. It’s through the use of the DOM, that JavaScript is able to access and alter the content and elements of the website.

To view the DOM, using your web browser, right click anywhere on a page and choose “Inspect”. This will open up Developer Tools, like so:

The DOM is shown under the Elements tab. You can also view it by selecting the Console tab and typing “document”.

The Document Object

The document object is a built-in object, containing many properties and methods.

We access and manipulate this object with JavaScript. And by manipulating the DOM, we can now make our web pages highly interactive! As we’re no longer limited to just building static sites with styled HTML content.

We can now build apps that update page data without needing to refresh, we can give users the ability to customize the page layout, we can create drag and drop elements, in-browser games, clocks, timers and complex animations. Working with the DOM opens up a whole lot of possibilities!

So let’s perform our first DOM manipulation..

Go to www.google.com and open up your Developer Tools. Then select the Console tab & type in the following:

document.body.style.backgroundColor = ‘orange’;

Hit enter and you’ll see the background color has now changed to orange.

Of course you haven’t edited Google’s source code (!), but you have changed how the content renders locally in your browser, by manipulating the document object.

The document is an object, body is a property which we’ve chosen to edit by accessing the style attribute & changing our backgroundColor to orange.

Note that we use camel case backgroundColor in JavaScript, instead of background-color which is used in CSS. Any hyphenated CSS property will be written in camelCase in JavaScript.

You can see your DOM adjustment under the body element of the Elements tab, or by typing document.body into the console.

As we are working directly with the DOM in the browser, we’re not actually altering the source code. If you refresh the browser it will return to its original state.

The DOM Tree & Nodes

Largely due to the layout of the DOM, it’s often called the DOM Tree.

The tree consists of objects called nodes. There are many different types of nodes, but you’ll most often be working with element nodes (HTML elements), text nodes (any text content) and comment nodes (commented code). The document object is its own node which sits at the root.

<!DOCTYPE html>
<html>
<head>
<title>Nodes</title>
</head>
<body>
<h1>This is an element node</h1>
<!-- This is a comment node -->
This is a text node.
</body>
</html>

When working with DOM nodes they’re also referred to as parents, children, and siblings, depending on their relation to other nodes.

In our above code example, the html element node is the parent node, the head and body elements are its siblings. And the body contains three child nodes (which are siblings in relation to each other — much like a family tree). We’ll look further into this later on in the article!

How to Identify Node Type

So every node in a document has a type, we can access the type using the nodeType property. See the full list of node types here.

Lets look at a few examples of the types that exist within our previous example:

Our <html>, <title>, <body> and <h1> are of the type ELEMENT_NODE with a the value of 1.

Our text This is a text node. located within the body which isn’t within an element is a TEXT_NODE with a value of 3.

And our comment <!-- This is a comment node --> is a COMMENT_NODE type with a value of 8.

How can we check our node types?

Go to the Elements tab in Developer Tools and click on any line. You’ll see the value of == $0 display alongside. Now if you go to the Console tab and type $0 the value of the node you selected will display. To check the node type, run:

$0.nodeType;

The numerical value of the node type, corresponding to the selected node will be displayed. e.g. If you had selected h1, you’d see 1. Doing the same for the text would yield 3, and the comment 8.

And when you know where the node sits in the DOM, you don’t need to manually select it, you can access it directly, for example:

document.body.nodeType;      // 1

You can also use nodeValue to get the value of a text or comment node, and nodeName to get the tag name of an element.

Accessing DOM Elements

In this section, we’re going to take a look at the methods we can use to access our DOM elements: getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector() and querySelectorAll().

We’ll be working with an HTML file that consists of a variety of elements, that way we can practice each method. The HTML is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Master the DOM!</title>
</head>
<body> <h1>Master the DOM!</h1> <div id="test">I'm an ID</div> <div class="test">I'm a class</div>
<div class="test">I'm another class</div>
<section>I'm a tag</section>
<section>I'm another tag</section>
<div id="test-query">Use a query selector</div> <div class="test-query-all">Use query selector ALL</div>
<div class="test-query-all">Use query selector ALL</div>
</body>
</html>

Our output looks like this..

getElementById()

Perhaps the most simple way to access a single element in the DOM is by its unique id. To do this we use the getElementById() method.

document.getElementById();

To access an element in this way it must have an id attribute. Such as:

<div id="test">I'm an ID</div>

With our HTML file open in the browser, open up the Console tab of Developer Tools. And let’s get that element and assign it to a variable named testId.

const testId = document.getElementById('test');

We can see the result with a console log:

console.log(testId);// output:  <div id="test">I'm an ID</div>

And let’s be sure we’re accessing the right element by giving it some style:

testId.style.backgroundColor = 'red';

Note: We’ll dive deeper into altering style later in the article!

Our live page will now look like this:

Accessing an element via its id is simple enough, however it can only connect you to a single element at a time (as id’s must be unique). So lets look at some more methods.

getElementsByClassName()

When we want to get one or more elements in the DOM, we can access elements by class name using getElementsByClassName().

document.getElementsByClassName();

In our example we have two elements with the class of test.

<div class="test">I'm a class</div>
<div class="test">I'm another class</div>

In the Console, lets get both of these elements and add them to a variable called testClass.

const testClass = document.getElementsByClassName(‘test’);

However, if we attempt to modify our elements in the same way we did with the previous ID example, we’d run into an error!

testClass.style.backgroundColor = 'green';// output:Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
at <anonymous>

This won’t work as instead of accessing one element, we’re accessing multiple elements which are stored in an array-like object.

console.log(testClass);// Output:HTMLCollection(2) [div.test, div.test]

When working with arrays, we access elements using an index number, the numbers start from 0. So we can change our first class element like so:

testClass[0].style.backgroundColor = 'green';

And to change all our class elements, we could use a for loop:

for (i = 0; i < testClass.length; i++) {
testClass[i].style.backgroundColor = 'green';
}

Note: I’ll be looking into the fundamentals of arrays and loops in future articles.

Here’s our updated example:

getElementsByTagName()

Another way to access multiple elements is via its HTML tag name using getElementsByTagName().

document.getElementsByTagName();

Here are the section elements in our example:

<section>I'm a tag</section>
<section>I'm another tag</section>

Lets add them to a variable:

const testTag = document.getElementsByTagName(‘section’);

Again, we’re working with an array-like object of elements, so lets modify all our section tags with a for loop.

for (i = 0; i < testTag.length; i++) {
testTag[i].style.backgroundColor = 'blue';
}

Query Selectors

Let’s take a look at our final element access methods querySelector() and querySelectorAll().

document.querySelector();
document.querySelectorAll();

To target a single element, we use the querySelector() method. Let’s access the following element in our example:

<div id="test-query">Use a query selector</div>

As it’s an id attribute, we use the hash # symbol when assigning our element:

const testQuery = document.querySelector(‘#test-query’);

If there were multiple instances of the element selected with querySelector(), only the first would be returned. To collect all elements matching a query, we’d use querySelectorAll().

Our example contains two elements with the test-query-all class:

<div class="test-query-all">Use query selector ALL</div>
<div class="test-query-all">Use query selector ALL</div>

As we’re now working with class attributes, we use the period . symbol to access our elements:

const testQueryAll = document.querySelectorAll(‘.test-query-all’);

And let’s use a forEach() method to modify our styles, like so:

testQueryAll.forEach(query => {
query.style.backgroundColor = 'yellow';
});

Additionally, query selector methods have the ability to work with multiple element types. For example:

querySelector('section, article') would match with whichever tag appears first, and:

querySelectorAll('section, article') would match with all section and article tags within the document.

Query selector methods are very powerful, you can use them to access any element or group of elements in the DOM — in the same way as you would when selecting elements in CSS.

Conclusion

And that concludes part 1! We’ve learned all about the DOM, and worked with the DOM tree and nodes to learn all about accessing and working with DOM elements.

In part 2, we’ll move on to traversing and modifying elements. See Master the DOM! (Part 2).

I hope you found this article useful! You can follow me on Medium. I’m also on Twitter. Feel free to leave any questions in the comments below. I’ll be glad to help out!

Next up in this series: Master the DOM! (Part 2).

Timothy Robards

Written by

Web Developer. Follow me for weekly posts on all things front end! https://timothyrobards.com 🔥🔥🔥

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade