Document Object Model (JavaScript)

An Introduction

Just Another Coding Blog
8 min readJul 13, 2021

A Document Object Model (DOM) is a programming API for HTML and XML Documents. It defines the logical structure of documents and the way these documents can be accessed and manipulated. The DOM can be used on any programming language.

Selecting, Creating and Deleting Elements

Selecting Elements

We can select certain Elements to help apply CSS Styles to the HTML page. For example;

console.log(document.documentElement);

console.log(document.head);

console.log(document.body);

We use the ‘.’ as the Selector.

const header = document.querySelector(‘.header’);

const allSections = document.querySelectorAll(‘.section’);

console.log(allSections);

We can also get the Element by their ID, instead of the whole list;

console.log(document.getElementById(‘section — 1’));

When using the Elements by Tag Name, the Elements will be returned as an HTML Collection, which is a Live Collection. If the DOM happens to change, the collection will be changed automatically as well;

const allButtons = document.getElementsByTagName(‘button’);

console.log(allButtons);

Getting the Elements by Class Name is similar to the getting the Elements by ID and Tag Name. It will also return an HTML Collection, which is a live collection.

console.log(document.getElementsByClassName(‘btn’));

Creating Elements

A quick and easy way to create an element is by using the ‘.insertAdjacentHTML’ into it. Let’s create a DOM Element and store it into a variable;

const header = document.querySelector(‘.header’);

const cookieMessage = document.createElement(‘div’);

cookieMessage.classList.add(‘cookie-cookieMessage’);

We can insert Text into the Page;

cookieMessage.textContent = ‘We Use Cookies for Improved Functionality and Analytics.’;

We can also insert it into the HTML;

cookieMessage.innerHTML = ‘We Use Cookies for Improved Functionality and Analytics. <button class =” btn btn — close-cookie”> Got It!</button>’;

This will generate a Cookie Message either on the top or the bottom of the page. To manipulate which end you want the message to display, you can either use;

header.prepend(cookieMessage);

Or

header.append(cookieMessage);

The prepend Method will add the element as the first child in our header element, whereas the append Method will add the element as the last child of the header element. In websites, it is usually best to have it in the bottom.

We can also add it before or after the header message;

header.before(cookieMessage);

Or

header.after(cookieMessage);

Deleting Elements

We can remove the Cookie Message after the User clicks on it by writing the following function;

document.querySelector(‘.btn — close-cookie’)

.addEventListener(‘click’, function () {

cookieMessage.remove();

});

This will remove the Cookie Message once clicked on the Button. There is also the older way of removing the elements;

document

.querySelector(‘.btn — close-cookie’)

.addEventListener(‘click’, function () {

cookieMessage.parentElement.removeChild(cookieMessage);

});

Styles, Attributes and Classes

We will be using the cookie message example above to showcase this section.

Styles

cookieMessage.style.backgroundColor = ‘white’;

cookieMessage.style.width = ‘auto’;

cookieMessage.style.fontSize = ‘18px’;

document.documentElement.style.setProperty(‘ — color-primary’, ‘orangered’);

This will change the message to white and will fit to the middle of the page once set to ‘auto’. The button will also change to orange-red.

We can also log the properties to see what exactly some of them are. However, some of the properties are hidden, so it won’t show;

console.log(cookieMessage.style.backgroundColor);

console.log(cookieMessage.style.height);

console.log(cookieMessage.style.color);

If we really wanted to get the properties, we can use the following;

console.log(getComputedStyle(cookieMessage).color);

We can also adjust the height by parsing a float value;

cookieMessage.style.height =

Number.parseFloat(getComputedStyle(cookieMessage).height, 10) + 20 + ‘px’;

This will adjust the height of the box of the cookie message. You cannot see it clearly, as we are using white as the background.

Attributes

The Attributes are defined as ‘src’, ‘alt’, ‘class’, ‘id’, etc. These attributes can be accessed and changed. For example;

const logo = document.querySelector(‘.nav__logo’);

console.log(logo.alt);

logo.alt = ‘Just a Different Logo’;

console.log(logo.alt);

console.log(logo.className);

We can also check for a non-standard property and how to identify them;

console.log(logo.designer);

console.log(logo.getAttribute(‘designer’));

console.log(logo.getAttribute(‘test’));

We can also set the attribute of the logo;

logo.setAttribute(‘company’, ‘343 Industries’);

console.log(logo.src);

console.log(logo.getAttribute(‘src’));

We can also get data attributes. These are special attributes that start with the word data. In the index, we use the ‘-’, whereas in the JavaScript file we use camel case.

console.log(logo.dataset.versionNumber);

This will give an output of the current version you have specified in the index page.

Classes

For Classes, we have methods that we can use to manipulate them;

logo.classList.add(‘class’, ‘join’);

logo.classList.remove(‘class’);

logo.classList.toggle(‘class’);

logo.classList.contains(‘class’);

We can also use this piece of code below to manipulate a class;

logo.className = ‘Test’;

However, this is not considered a good practice as it will override all the existing classes.

The Types of Events and Event Handlers

We can use Events and Event Listeners to manipulate a piece of text or HTML to our preference. A simple example is given below;

const h1 = document.querySelector(‘h1’);

const alertH1 = function () {

alert(‘You are reading this for no reason’);

};

h1.addEventListener(‘mouseenter’, alertH1);

The mouse enter method will fire once the mouse hovers over the h1 paragraph. We can also use a set timeout function to remove the event listener after a certain period of time. If not, it will keep firing every time the mouse hovers over the h1 paragraph.

setTimeout(() => h1.removeEventListener(‘mouseenter’, alertH1), 2500);

Using Event Listeners is a lot more feasible because it allows to add multiple event listeners to the same event. The Event handler can be removed if there is no more requirement for it. To do this, we can export the function into a named function;

h1.onmouseenter = function () {

alert(‘You are reading this for no reason’);

};

Event Propagation

We can use event propagation to help manipulate certain fields. An example is given below;

const randomNumber = (minimum, maximum) =>

Math.floor(Math.random() * (maximum — minimum + 1) + minimum);

const randomColor = () =>

`RGB(${randomNumber(0, 255)}, ${randomNumber(0, 255)}, ${randomNumber(0,255)})`;

We are going to change the color's of the navigation bar to a random color.

Changing the Color of one Link

document.querySelector(‘.nav__link’)

.addEventListener(‘click’, function (event) {

this.style.backgroundColor = randomColor();

console.log(‘Link’, event.target, event.currentTarget);

console.log(event.currentTarget === this);

});

This will change the first link in the navigation bar once clicked on;

The console.log is given below;

Changing the Color of all Links

document.querySelector(‘.nav__links’)

.addEventListener(‘click’, function (event) {

this.style.backgroundColor = randomColor();

console.log(‘Container’, event.target, event.currentTarget);

});

This will change the color of the entire navigation bar once clicked on;

We can write a piece of code to stop propagation in these methods. However, it has its ups and downs. It can be used to fix problems that have many handlers for the same event. However, it is not a good idea to stop propagation for certain events;

document.querySelector(‘.nav__link’)

.addEventListener(‘click’, function (event) {

this.style.backgroundColor = randomColor();

console.log(‘Link’, event.target, event.currentTarget);

console.log(event.currentTarget === this);

event.stopPropagation();

});

DOM Traversing

Elements in the DOM are organized into a tree-like data structure which can be traversed to navigate, modify or locate elements and content within an HTML/XML Document.

const h1 = document.querySelector(‘h1’);

Traversing downwards by selecting Child Elements

console.log(h1.querySelectorAll(‘.highlight’));

console.log(h1.hasChildNodes());

This will only work for direct children elements;

console.log(h1.children);

h1.firstElementChild.style.color = ‘white’;

h1.lastElementChild.style.color = ‘orangered’;

This will change the h1 highlighted background color to orange-red;

Traversing upwards to select the Parent Elements

console.log(h1.parentNode);

console.log(h1.parentElement);

The parent node and parent element are basically the same in this instance.

However, we need a parent element that is not a direct parent, or we need to find a parent element no matter how far it is in the DOM Tree, so we use the closest method for this. The closest method can be seen as the opposite of querySelector;

h1.closest(‘.header’).style.background = ‘var( — gradient-secondary)’;

h1.closest(‘h1’).style.background = ‘var( — gradient-primary)’;

This will change the entire background. This is because it selected the closest parent element to h1, which is the header. Then, it applied the background color. This is used for Event Delegation frequently.

Traversing sideways to select the Sibling Elements

In JavaScript, we can only access the direct siblings (only the previous and the next sibling).

console.log(h1.previousElementSibling);

console.log(h1.nextElementSibling);

console.log(h1.previousSibling);

console.log(h1.nextSibling);

The previous sibling is listed as null because h1 is the first element. The next sibling is h4, which is listed above.

Moving up the Parent Element to Read all Children Elements

This will basically show all the children elements;

console.log(h1.parentElement.children);

We can also manipulate the HTML collection by changing it into an Array;

[…h1.parentElement.children].forEach(function (element) {

if (element !== h1) {

element.style.transform = ‘scale(0.5)’;

}});

This will scale all the children elements to 0.5 that is not h1, so only h4.

Lifecycle DOM Events

These are events that will occur during the web pages lifecycle. This means when the user first accesses the page till the user leaves the page.

The DOMContentLoaded event does not wait for images and other external resources to load. Only HTML and JavaScript need to be loaded.

document.addEventListener(‘DOMContentLoaded’, function (event) {

console.log(‘HTML Parsed and DOM Tree Built’, event);

});

We want all the code to be executed after the DOM is ready, so we use a script tag at the end of the index html body.

<script src=”script.js”></script>

When the page has fully loaded, this event will be fired. This is just a regular event object.

window.addEventListener(‘load’, function (event) {

console.log(‘Page Fully Loaded’, event);

});

We can also ask the user if they are sure of leaving the page by using an event;

window.addEventListener(‘beforeunload’, function (event) {

event.preventDefault();

console.log(event);

event.returnValue = ‘’;

});

--

--