DEV Community

Cover image for Understand The DOM and DOM manipulation with javascript. (part 1)
Jonathan Zihindula
Jonathan Zihindula

Posted on • Edited on

Understand The DOM and DOM manipulation with javascript. (part 1)

In this artcle we are going to get an understanding of Document Object Model known as DOM.
The words DOM are used by developers and can be found all over the internet. However you may not be quite sure of what is it exactly.Don't worry you're on the good place.

I. The DOM, and DOM construction

I.1 The DOM

The DOM (Document Object Model) is a programing interface for the web document , it represents the page as an object so that programing languages can access to and modify the document (web page) structure , style , etc.

I.2. DOM construction

As DOM is the object model of the HTML document, let's understand step by step how this object is contructed by the browser.

step 1

No mater which backend is used , when we request a web page , it responds as an HTML, on the first step HTML document is received.

step 2

HTML is composed by tags (starting and ending tags). For each tag the browser emits a token.

<html>
    <head>
         <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <link rel="stylesheet" href="index.css" />
          ...
    </head>
</html>

Enter fullscreen mode Exit fullscreen mode

From the code above, the browser will emit first the start tag html token, next the browser emit start tag head token , and so on. This process is done by the Tokenizer.

step 3

while the tokenizer is generating and emitting tokens , those ones are consumed and converted into nodes.
From step two, we may have after consuming start tag html token a html node , next head node, then meta node, then link node.

You may ask, how the browser knows that head tag is a child of html tag ?😕️.
Well, good question. As the starting tag head token was emitted before the endig tag of html token, its means the head tag is a child of html tag.

DOM tree

The image above shows how nodes are linked to each other .

Note: In the DOM each tag contains all its related attributes as well.

step 4

Now , we have all the nodes and their related attributes , the browser builds the Object representation of our HTML document.

All the step of DOM construction can be represented by the image below.

DOM step by step

characters are the tag symbols < , >.

II. DOM manipulation with Javascript

The DOM is not a part of javascript language as we can think , however it can be accessed and manipulated by javascript using the special object provided by the browser document.

II.1 Select unique Element

II.1.a Select Element by ID

Said previously, DOM is an object representation of HTML document, means it has key: value pair. Some of them are properties and others are methods that provid some fonctionalities.

The first DOM method that we will be loocking at is getElementById().


document.getElementById("myElementId");

Enter fullscreen mode Exit fullscreen mode

The above method receives an argument which is the id of the element that you want to select or you want to have access to.


<!DOCTYPE html>
<html lang="en">
   ...
  <body>
    <h1 id="title">Home page title</h1>

    <script src="./index.js"></script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

To get the h1 tag using its id we can use the following code.


 const myHomePageTitle = document.getElementById("title");

Enter fullscreen mode Exit fullscreen mode

The getElementById("myId") method returns an Element object representing the element whose id property matches the specified string passed as argument.
Readmore about this method here.

II.2. Select multiple Elements

II.2.1 Select Element by class

The second way to select a HTML elements, is by using the class attribute.


document.getElementsByClassName("myClassName");

Enter fullscreen mode Exit fullscreen mode

Also this method , revceives a class of the elements we want to select and return an HTMLCollection.

Get element by class name illustration

The image above illustrates the type of value returned by the getElementsByClassName() method.

II.2.2 Select Element by tag

The second way of selecting multiple element is by using element's tag name. As the tag is not always unique , the following method returns an HTMLCollection as well.


document.getElementsByTagName("div");

Enter fullscreen mode Exit fullscreen mode

This method needs the tag name that we want to select as argument, this may be div, p,span,etc.

II.2.3 querySelector() and querySelectorAll()

These are two more mays of selecting multiple elements, but f querySelector() and querySelectorAll() methods need an element selctor like in css in its argument.


document.querySelector("#id"); // to select element by Id

document.querySelectorAll(".class"); // to select elements by class

Enter fullscreen mode Exit fullscreen mode

The .querySelector() method will always return the first element whose the id or class match the specified string passed as argument. While the .querySelectorAll() will return an NodeList of element that the specified selector matches with.

Note

HTMLCollection and NodeList are not arrays as we can think at the first look. However they can be transformed into an array then be manipulated as arrays. The code bolow illustrate one of the ways to transform a HTMLCollection or NodeList


const panels = document.querySelectorAll(".panel"); // return a NodeList

const panelsToArray = Array.from(panels) // return an array

Enter fullscreen mode Exit fullscreen mode

Read more about DOM interfaces here

III. Modify Page Content

We are able to select an element , now , we are going to understand how to update the content on page using the DOM.

III.1. innerHTML property

innerHTML is an Element (Elemement Interface) property that allows to get or set HTML or XML content of an element.


<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

Enter fullscreen mode Exit fullscreen mode

const list = document.getElementById("list");

console.log(list.innerHTML) // return "<li>Item 1</li><li>Item 2</li><li>Item 3</li>" as a DOMString not a string

list.innerHTML += "<li>Item 4</li>"; // add a new *li* tag with **itme 4** as content

Enter fullscreen mode Exit fullscreen mode

III.2 textContent and innerText properties

textContent and innerText can be confusing but there still difference.

  • textContent: gets the content of all elements, including <script>and <style> elements. In contrast, innerText only shows "human-readable" elements, means innerText will consider the css style.
<ul id="list">
  <li class="list__item">Item 1</li>
  <li class="list__item list__item--hidden">Item 2</li>
  <li class="list__item">Item 3</li>
</ul>
Enter fullscreen mode Exit fullscreen mode
...

.list__item--hidden{
   display: none;
}

...

Enter fullscreen mode Exit fullscreen mode

const list = document.getElementById("list");

console.log(list.textContent);
// return Item 1 Item 2 Item 3

console.log(list.innerText);
// return item 1 item 3 because Item 2 is hidden by css style

Enter fullscreen mode Exit fullscreen mode

IV. Conclusion

  • DOM is not part of javascript language
  • DOM is constructed from the browser
  • DOM is globally accessible by JavaScript code using the document object

In this article we learned what is DOM, and how to access and update content on the page using DOM. You can find the next part where we focus on how to add and remove content on the page here.

Top comments (2)

Collapse
 
brendahuwitonze profile image
Brendah Uwitonze

This was really helpful

Collapse
 
edsonpro profile image
edson-pro

Good article