Skip to main content

A lifetime of knowledge at your fingertips.

Choose from hundreds of books, courses, and tech talks on web development. Learn HTML, CSS, and JavaScript to React, Docker, and Python.

Create Account
code world

Trusted by over 100,000 developers from...

99designs
Microsoft
Shopify
Stanford University

Develop valuable new skills.

Search our library of over 600 books, courses, and tech talks. New content added every week.

Why choose SitePoint?

Build your tech knowledge across any subject. We give you everything you need.

library

Explore a Huge Library

Get access to over 600 books, courses, and videos. Learn twice as fast with the ultimate text-based learning experience.

fresh

Get Fresh Content Weekly

We’re constantly adding new content on web development, design, and technology.

community

Join a Vibrant Community

Join 100,000 developers and designers. Discuss new tech, get fast feedback, and a helping hand when you’re stuck.

The ultimate text-based learning experience.

Text-based learning is proven to be twice as fast as video or audio lessons. We've also added some extra features to make your web development education even easier:

  1. Live interactive code environments

  2. Bookmark sections to read later

  3. Share snippets with peers and coworkers

  4. Choose a super comfortable Dark Mode

JavaScript: Novice to Ninja, 2nd Edition Dashboard Library Bookmark Send a Link 1 Write and edit code in alive coding environment without leaving your book. 2 Bookmark your favorite text and code samples for later reference. 3 Easily share text and code samples with friends - even if they don’t have the book. 4 Give your eyes a break while taking your learninginto the night. </> FILETREE ~/workspace heroes notes.txt quiz </> LIVE CODE window.onload=function() { setTimeout(() => { const quiz = [ { name: "Superman",realName: "Clark Kent" }, { name: "Wonder Woman",realName: "Diana Prince" }, { name: "Batman",realName: "Bruce Wayne" }, ]; const game = { start(quiz){ this.questions = [...quiz]; this.score = 0; // main game loop for(const question of this.questions){ this.question = question; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 main.js styles.css heroes.h.. notes.txt Open an HTML file to view Web Browser Send as a link to this paragraph Anybody with this link can view this part of the book. https://www.sitepoint.com/premium/books/learn-to-code-with- javascript/read/1/kml7wxl6?fromShare=true Copy Link
The Document Object
Model
Darren Jones
Chapter 6
The Document Object Model (DOM) allows you to access elements of a web page and enable interaction with the page by adding and removing elements, changing the order, content and attributes of elements, and even altering how they are styled.
In this chapter, we’ll cover the following topics:
  • Introduction to the DOM
  • Getting elements ― getElementByIdgetElementsByClassNamegetElementsByTagNamequerySelector and querySelectorAll
  • Navigating the DOM
  • Getting and setting an element’s attributes
  • Updating the DOM by creating dynamic markup
  • Changing the CSS of an element
  • Our project ― we'll dynamically insert each question into the HTML
The Document Object Model
What is the DOM?
The Document Object Model, or DOM for short, represents an HTML document as a network of connected nodes that form a tree-like structure.
The DOM treats everything on a web page as a node. HTML tags, the text inside these tags, even the attributes of a tag are all nodes. The HTML tag is the root node, and every other part of the document is a child node of this.
Take the following piece of HTML as an example:
<p class='warning'>Something has gone <em>very</em> wrong!</p>
This can be represented as the tree diagram shown below.
p.warning #text #text #text em
The DOM tree
The DOM is not actually part of JavaScript because it is language agnostic (although JavaScript is, by far, the language most commonly used with it). This means it can be used in any programming language, not just JavaScript. We can use JavaScript to access and modify different parts of a web page using a special built-in object called document.
History of the DOM
In the early days of the web, browser vendors such as Netscape and Microsoft developed their own distinct ways of accessing and altering parts of a web page. In the beginning, they tended to focus on common page elements such as images, links and forms – this was known as Dynamic HTML (DHTML). These methods became known as DOM level 0, or legacy DOM. Some of the more common methods, such as those used for selecting images and forms, can still be used in the current DOM.
The World Wide Web Consortium (W3C) started to standardize the process, and created the DOM level 1 in 1998. This introduced a complete model for web pages that allowed every part of them to be navigated.
The DOM level 2 specification was published in 2000 and introduced the popular getElementById() method, which made it much easier to access specific elements on a web page. The DOM level 3 specification was published in 2004, and since then the W3C has abandoned using levels. The DOM specification is developed as a living standard.
Despite the standardization process, browsers have not always implemented the DOM consistently, so it’s been difficult to program for in the past. Fortunately, since Internet Explorer 8, DOM support has been much more consistent, and modern browsers now implement the current DOM level 3. They’re also implementing more of the new DOM level 4 features with every update.
An Example Web Page
To illustrate the DOM concepts covered in this chapter, we’ll use a basic web page that contains a heading and three paragraph elements. Save the following code in a file called heroes.html :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Justice League</title>
</head>
<body>
<header>
<h1 id='title'>Justice League</h1>
</header>
<ul id='roster'>
<li class='hero'>Superman</li>
<li class='vigilante hero' id='bats'>Batman</li>
<li class='hero'>Wonder Woman</li>
</ul>
</body>
</html>
Below is a node tree diagram for the  <ul> element with a class of roster :
What's With the Extra Text Nodes?
There appear to be some extra #text nodes in this diagram, even in places where there isn't any text. This is because the DOM also stores any whitespace that is in the HTML document as text nodes.
Because we're using the browser, the best way to follow along with the examples in this chapter is to use the console built into the web browser (we discussed how to use this in Chapter 1). This will allow you to enter commands that interact with the elements on the web page and see the results. The screenshot below shows the page with the console open.
Console Shortcuts
Here are a couple of useful shortcuts that will help speed things up when you're using the console:
  • Pressing TAB will autocomplete any methods and should show you a list of possible methods
  • Pressing the UP arrow key will select the previous command entered.
Getting Elements
The DOM provides several methods that allow us to access any element on a page. These methods will return a node object or a node list, which is an array-like object. These objects can then be assigned to a variable and be inspected or modified.
For example, we can access the  body element of a web page and assign it to the variable body by entering the following code into the browser console:
const body = document.body;
Now we have a reference to the body element, we can check its type:
typeof body;
<< "object";
This is a special Node object with a number of properties and methods that we can use to find information about, or modify, the body element.
For example, we can use the nodeType property to find out what type of node it is:
body.nodeType;
<< 1
All nodes have a numerical code to signify what type they are. These are summmarized in the table below.
Code Type
1 element
2 attribute
3 text
8 comment
9 body
There are other types not covered in the table, but these aren’t used in HTML documents. As we can see from the table, a code of 1 confirms that body is an element node.
We can also use the nodeName property to find the name of the element:
body.nodeName;
<< "BODY"
Note that the element name is returned in uppercase letters.
This is a live reference to what is displayed in the browser. You can see this by hovering your cursor over the reference in the console and see it highlighted in the main viewport, as illustrated in the screenshot below:

Get unlimited access to SitePoint Premium now!

  • Unlimited access to our entire library of courses and books.
  • Join the SitePoint community of over 100,000 developers.
  • No lock ins, cancel at any time.
$6
$9
/month
(Billed annually at $72.)

Don’t leave home. Watch the world’s most inspiring Tech Talks right here.

Get cutting-edge techniques directly from the experts. Straight to your screen from Amsterdam, San Francisco, Manchester, or Melbourne.

Browse All Talks

Tap into the world’s leading web development publishers.

A Book Apart
Wiley
SitePoint
Smashing Magazine

Practical, hands-on video courses on the topics you need.

Watch concise video courses that walk you through the tricky parts. For those times when you need to see how things are done on someone else’s screen.

Browse All Courses

Here's what our members think:

Dane M.Dane M.Web Developer

SitePoint is my first line of education for website development and design. I’ve been a member for several years and I use it consistently month in and month out...

Nilantha

Nilantha

Tech Consultant

I am very new to PHP but within a shorter period of time I was able to provide software solutions to major companies in my country. Recently I was struggle to know the hashing password and came across your article which helped me very well to overcome the situation.

Linda

Linda

Self Taught

SitePoint's books taught me so much over the years, and I've been most grateful for the quality instruction in them.

Read our newest articles:

Read All Articles