DOM — The Tree of the Browser

Winston Chen
6 min readJan 14, 2021
Photo by Todd Quackenbush on Unsplash

What is the DOM? The DOM, or Document Object Model, is a cross-platform and language-independent interface that treats an HTML document as a tree structure wherein each node is an object representing a part of the document.

Imagine a tree. Each branch of that tree ends in a node, and each node contains objects. DOM methods allow programmers to access the tree so that they can change the structure, style or content of a document. Nodes can have event handlers attached to them. When this event is triggered, the event handlers get executed.

We can’t talk about the DOM without first talking about the browser. When we make an HTTP request, we get the page and we get the html, but what the browser does with the html is start to split it up into this things called the document object model. For example, when we make a request to wikipedia, wikipedia sends as a response, the html page — then our browser catches that html and then immediately starts to parse that out into this tree called the DOM. This document is the global object for the entire page.

The Duo: DOM and JavaScript

Every element in a document , you name it — the document as a whole, the head, tables within the document, table headers, text within the table cells — is part of the document object model for that document. These things can all be accessed and manipulated using the DOM and a scripting language like JavaScript. With the object model, JavaScript gets all the power it needs to create dynamic HTML:

  • Can change all the HTML elements in the page
  • Can change all the HTML attributes in the page
  • Can change all the CSS styles in the page
  • Can remove existing HTML elements and attributes
  • Can add new HTML elements and attributes
  • Can add new HTML elements and attributes
  • Can react to all existing HTML events in the page
  • Can create new HTML events in the page

Any change that we do to the DOM with JavaScript is reflected into the browser.

Here is what we can do in the JavaScript Console to access different parts of the browser:

document (the global object for the entire page - contains everything) - also can be thought of as the parent of the whole tree structuredocument.children
document.children[0].children
document.children[0].children[1].children

Easier way than above to call DOM methods. The first one we will talk about is document.queryselector so let’s look at that one specifically. You can find this information at developer.mozilla.org.

element = document.querySelector(selectors);header = document.querySelector('.') - for class
header = document.querySelector('#') - for id
header = document.querySelector('div') - for tag

If there’s some element of the DOM that we want to access in some way, we will use the document or if we know a nested node right off the top of our head that we want to call on, then we’ll call that note. It has to be a node. Here is an example in which we access the header with an id:

header = document.querySelector('#mp-tfa-h2')

To change the header, we have to call some property of it:

let text = someNode.textContent header.textContent = "New Content"

There are so many DOM methods, so it’s good to practice Googling them, but here is a short guide to the most popular ones:

DOM Methods

Here are some additional ones that might come in handy:

Let’s practice using the above methods:

function changeAllComments() {
// Grab the DOM elements

let comments = document.getElementsByClassName("list-group-item")
let comments2 = document.querySelectorAll(".list-group-item")
}console.log(comments, comments2);changeAllCOmments()

Now, we want to loop through using forEach:

function changeAllComments() {

let comments2 = document.querySelectorAll(".list-group-item")
comments2.forEach(function(comment){
comment.innerText "Hey I'm changing!"
})
}

So, if we want to loop over a set and perform some sort of action on each dom element, we cannot do that on a html collection. We have to do it, instead, on a node list. That is why we can use getElementsByClassName and not querySelectorAll.

We can do a lot of things with node list that we can’t do with HTML collections. Almost never when looping would you use an HTML collection. In general, will use querySelector or querySelectorAll.

Here is another way of getting the same response as above:

function changeAllComments() {

let comments2 = document.querySelectorAll(".list-group-item")
let changeText = function(comment){
comment.innerText "Hey I'm changing!"
}
comments2.forEach(function(changeText)
}

How about appending something on the DOM? So here are the steps to approach it:

  1. Grab the box where the collection live
  2. Create the DOM element for that comment
  3. We have to take the text from the args and plug it into the new DOM element
  4. Append that DOM element to the DOM
function addComment(text) {   let commentBox = document.querySelector('.list-group')
let newComment = document.createElement('li')
newComment.innerText = text

commentBox.appendChild(newComment)
}addComment("Adding some text") *innerText is a property and we set properties with an equal sign

Pro-tip: If there are a bunch of class names, then just modify the HTML (such as adding an ID) so that it is easier to program

To create a DOM element in JavaScript, we must:

const e = document.createElement('div');

How about changing the CSS as well? Well, we would need this syntax:

document.getElementByID (id).style.property = new style

Or we can also add a class name if style is already incorporated into the class, like so:

function addComment(text) {let commentBox = document.querySelector('.list-group')
let newComment = document.createElement('li')
newComment.innerText = text
newComment.className = "list-group-item"
commentBox.appendChild(newComment)}addComment("Adding some text")

Here is another approach to what we have above:

function addComment(text) {   let newComment = document.createElement('li')
newComment.innerText = text
newComment.className = "list-group-item"
document.querySelector('.list-group').appendChild(newComment)}addComment("Adding some text")

So instead of running querySelector at the beginning, we are running that method directly, in what’s called chaining and appendChild at the end of it.

Can also change the background color. Here is an example:

function addComment(text) {let newComment = document.createElement('li')
newComment.innerText = text
newComment.className = "list-group-item"
newComment.style.background = "Blue"
document.querySelector('.list-group').appendChild(newComment)}addComment("Adding some text")

Can also create a form using a function:

function addForm(){
let container = document.querySelector('.container')
let newDiv = document.createElement('div')newDiv.innerHTML = `<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form> `
container.appendChild(newDiv)
}
addForm()

Last thing, we’re going to use a DOM method to delete a comment, going off the example from above:

function deleteComments(){
let commentBox = document.querySelector('.list-group')
commentBox.innerHTML = ""
}

Here is another approach to that shown above:

function deleteHeader() {
let header = document.getElementById("card-title")
header.remove()
}
deleteHeader()

So all of the above is DOM-manipulation in a nutshell.

That’s about it, but remember that your best friend for all of this is: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction

…so make sure to take full advantage of this when you’re investigating the DOM!

DOM Resource

--

--

Winston Chen

Full-Stack Web Developer, specializing in React and Ruby on Rails.