Ionut Andrei Dirlea

The DOM

January 04, 2020 - 4 min read
Personal blog of Ionut Andrei Dirlea
I write about JavaScript, React, Swift, Swift UI and love of coding

The document object model or DOM is a programming interface for HTML and XML documents. It represents the page into a tree like structure so computer programs like JavaScript can change the document structure, style or content. The tree’s nodes are objects with properties and methods and the topmost node is the document object.

<html>
	<head>
    <title>The DOM</title>
  </head>
	<body>
    <div id=“wrapper”>
      <header>
        <p>The Document Model</p>
      </header>
			<main>
        <div class=“text”>The DOM tutorial</div>
				<div class=“text”>Is the DOM slow?</div>
      </main>
    </div>
  </body>
</html>

1. Accessing one element

For accessing one element we will take a look at 2 methods: getElementById and querySelector

// getting an element by it’s id
const element = document.getElementById(‘wrapper’)
element.style.color = ‘red’

// select the p inside the header
const q = document.querySelector(‘header p’)
q.style.fontSize =20px’

getElementById takes as argument the id name of the element and querySelector takes as argument a CSS selector and returns the first element that matches the selector.

2. Accessing more than one element

To get more elements we’ll look at 3 methods: getElementByClassName, getElementsByTagName and querySelectorAll.

const elements = document.getElementByClassName(‘text’)

// print all elements that have the class of text
console.log(elements)

// print the first element
console.log(elements[0])

const elementsByTag = document.getElementsByTagName(‘p’)
const elementsByQueryAll = document.querySelectorAll(‘header p’)

The getElementsByClassName takes an argument a name of a class. It returns a node list of all the elements that have the class of ‘text’. As you can see in the example above the elements can be accessed using the array notation and the item method.

In the second example we select every p elements using getElementsByTagName method that takes the name of the tag as an argument.

Finally, we use the querySelectorAll method, that takes as an argument a CSS selector. The method will return a node with a list of all p elements inside of div

3. Traversing the DOM

So until now we saw how to access specific elements. Now let’s see how to access an element that is next to the element that we already accessed or the parent node of the selected node? For this scenarios we have a few properties: firstChild, lastChild, parentNode, nextSibling, previousSibling.

The naming of the properties is self explanatory so I won’t go through them. Instead let’s see an example:

const first = document.getElementById(‘wrapper’).firstChild
console.log(first)

const last = document.getElementById(‘wrapper’).lastChild
console.log(last)

const parent = document.getElementById(‘wrapper’).parentNode
console.log(parent)

const sibling = document.getElementsByClassName(.text’)[0].nextSibling
console.log(sibling)

4. Creating elements

To create new DOM elements is simple you just need a few lines of JavaScript. Let's see an example:

<html>
	<head>
    <title>The DOM</title>
  </head>
	<body>
    <div class=“text”>Adding new DOM element</div>
		<script>
	    let div = document.createElement("div")
			div.innerText = 'Alex'
			document.body.appendChild(div)
    </script>
  </body>
</html>

As you can see to create a new element we gone use the createElement method and we need to pass the string of the element we want to create. This can be any html element div, span, img. I added the element on the body but we can call appendChild on any element.

5. Removing elements

Removing elements is as simple as adding a new one. Let's see an example:

<html>
	<head>
    <title>The DOM</title>
  </head>
	<body>
    <div class=“text”>Adding new DOM element</div>
		<div id="to-remove">This is an example of removing elements using JS</div>
		<script>
	    let elementToRemove = document.getElementById('to-remove');
			elementToRemove.paretNode.remove(elementToRemove)
    </script>
  </body>
</html>

We remove the element with 2 lines of code. We need to get the element that we need to remove. To actually remove it we need to go up one level to his parent and call the remove method and pass the element to remove as an argument. An we are done the element is removed.

I hope you liked this post and you learn more about JavaScript.