DOM Manipulation in A Nutshell

Fernando Putra
6 min readDec 5, 2021

--

Background from Kurzgesagt

One of the essential things to master while creating web pages and apps is manipulating the document structure. This is usually done by using the Document Object Model (DOM).

In this article, we’ll look at the DOM, how to use it, and some of the most useful functions and properties of DOM manipulation in JavaScript.

What Is DOM?

DOM is an acronym that stands for Document Object Model. Its robust tree-like structure allows programmers to conceptualize hierarchy and access the elements on a web page. A helpful way to understand what DOM does is by breaking down the acronym but out of order:

The DOM is a logical tree-like Model that organizes a web page’s HTML Document as an Object.

The HTML DOM model is constructed as a tree of Objects

When a web page is loaded, the browser creates a DOM of the page. The topmost node is called the root node, representing the HTML document. The descendants of the root node are the HTML tags in the document, starting with the <html> tag, followed by the <head> and <body> tags, and so on.

How to use it?

The DOM allows for web scripting languages, like JavaScript, to access, modify, and update the structure of an HTML web page in an organized way using the document object’s API.

The document object in JavaScript is the door to the DOM structure. It allows us to access the root node of the DOM tree. Before accessing a specific element on the page, you must first access the document structure itself. This document allows scripts to access children of the DOM as properties.

For example, if you wanted to access the <body> element in your script, you could access it as a property of the document by typing document.body. This property will return the body element of that DOM.

Tweak an Element

element.innerHTML property returns the HTML content of an HTML element. For example, the following code reassigns the inner HTML of the body element to the text ‘Hello World.’:

document.body.innerHTML = 'Hello World.';

The .innerHTML property can also add any valid HTML, including properly formatted elements. The following example assigns an h2 element as a child inside the <body> element:

document.body.innerHTML = '<h2>This is a heading</h2>';

Accessing Elements

We can access a specific markup element using its identifier or a collection of elements by their name, class type, tag name, and several other aspects in many ways:

1. document.querySelector()

document.querySelector() is a function that takes a CSS selector as a parameter and then returns the first matched element with the selector provided. This is the recommended modern approach when selecting an element because it allows us to select elements using CSS selectors.

const link = document.querySelector('a');

In the code above, we store the element node associated with the <a> element in a variable named link.If no element is found using that particular selector, the function will return as null.

2. document.querySelectorAll()

If we wanted to match and do things to multiple elements, we could use document.querySelectorAll(), which matches every element in the document that matches the selector and stores references to them in an array-like object called a NodeList.

var todoItems = document.querySelectorAll('#todos > li');

In the code above, we store all of the list’s items in a variable using document.querySelectorAll().Once we have stored the element nodes, they can be accessed just like items in an array.

3. document.getElementById()

If an element has an id attribute, we can use the document.getElementById() function, which selects an element with a given id attribute value that is passed to the function as a parameter.

document.getElementById('bio').innerHTML = 'The description';

In the code above, we chain the document.getElementById() with the .innerHTML property so that it selects the element with an ID of ‘bio’ and sets its .innerHTML to the text 'The description'

4. document.getElementsByTagName()

This function is similar to the document.querySelectorAll() , which returns an array-like object with all the elements on the page that match with the giventagName , for example body, div, h3, br, etc.

var paragraphs = document.getElementsByTagName('p');

Both of getElementById() and getElementsByTagName() are the older methods for grabbing element references. These two work better in older browsers than the modern methods like querySelector(), but are not as convenient asquerySelector().

Adding Elements

Just as the DOM allows scripts to modify existing elements, it also allows for creating and removing elements.

To create a new element, we can use document.createElement() with the argument of element, which is the element name. However, it does not append it to the document. It creates an empty element with no inner HTML.

To add it to the HTML page, we must append the element as a child of an existing element on the DOM. We can use the Element.appendChild(element_node) to add a child element as the last child node.

let newTask= document.createElement('li');
newTask.innerHTML = 'Oaxaca, Mexico';
document.getElementById('list-of-tasks').appendChild(newTask);

In the code above, we create a new li element and save it in a variable called newTask, adds text to the new element’s .innerHTML, and then appends it as the child of the list with the ID list-of-tasks .

Removing Elements

You can use Element.removeChild() to remove a child from a parent element within the HTML document. The function will return the removed element.

const parent = document.querySelector("#content");
const child = document.querySelector("#content > p");
parent.removeChild(child);

In the code above, we select the parent element with the ID content and save it to a variable, select its child, and save it to a variable child . Then, we remove the element using the .removeChild() method and pass in the child variable.

Modifying CSS

The easiest way to change CSS styles on an HTML element using Javascript is to access individual styles in the Element.style property. The .style property of a DOM element provides access to the inline style of that HTML tag.

The syntax follows an element.style.property format, with the property representing a CSS property.

document.querySelector('.background').style.backgroundColor = 'blue';

In the code above, it selects the element with a class of background querySelector()and sets its background color to blue, using style.backroundColor

If you notice, unlike CSS, the DOM style property does not implement a hyphen, such as background-color, but rather camel case notation backgroundColor.

Many CSS properties can be accessed within Element.style. A complete list can be found here. Browse through the list to understand the different properties you can target using Javascript.

Event Listeners

We can add interactivity to DOM elements by assigning a function to run based on an event. Events include anything from a click to a user mousing over an element. For example:

var button = document.querySelector('button');
button.onmouseenter = function(){this.innerHTML = "Mouse entered!";}
button.onmouseleave = function(){this.innerHTML = "Mouse left!";}
button.ondblclick = function(){this.innerHTML = "Double clicked!!";}

There are many different kinds of events that occur in the browser. A few examples include:

Mouse Events: Events that occur with a user’s mouse.

  • ondblclick: occurs when an element is double-clicked.
  • onmouseenter: occurs when the mouse pointer moves onto an element.
  • onmouseleave: occurs when the mouse pointer moves away from an element.

Keyboard Events: Events related to key presses on the user’s keyboard.

  • onkeypress: occurs when a key is pressed on the user’s keyboard.
  • onkeydown: occurs when a user is pressing down on a key.
  • onkeyup: occurs when a user releases a key press.

Form Events: Events related to interactions with form elements, such as <input>.

  • onfocus: occurs when the focus is placed on an <input> field.
  • onchange: occurs when an <input> value is changed (useful for radio or checkbox type inputs).
  • oninput: occurs when a user provides input to an element (useful for text type inputs or <textarea> elements).

Great, you have learned the basics of DOM Manipulation. I hope this article helped you to get started with the DOM 😁.

Thank you for reading! If you found this article helpful, kindly share it with your friends and follow my profile for future updates. Your support is much appreciated! PS: It would mean even more if you donate a pizza 🍕 here. ✌️

--

--