A guide to manipulating the DOM like a pro with JavaScript

Last updated: September 27, 2022.

JavaScript was created for manipulating the DOM. To become proficient in using JavaScript, it is therefore essential to become fluent in its most important DOM manipulation methods and techniques.

This tutorial guide provides an overview of everything you need to know be able to start manipulating the DOM like a pro! πŸ±β€πŸ‘€

We start by looking at how to create, add and remove nodes and elements from the DOM. Following this, we look at how you can set and create element attributes. Finally, we cover how to directly edit the styling of an element.

Creating a new element πŸ†•

A new HTML element of any type can be created by calling the document.createElement method and passing in a valid element type as a string.

Note that doing so creates the element, but does not place it on the page. For this, one of the methods for adding an element in the DOM should be used after creating the element.

/***  Using document.createElement() ***/

const myDiv = document.createElement('div'); // creates new div element

const newArticle = document.createElement('article'); // creates new article element

const spanElement = document.createElement('span'); // creates new span element

Adding elements to the DOM βž•

element.append()

The append method can be applied to any DOM element (including document.body) and accepts an element or a node (e.g. plain text).

What is passed into it will appear last inside the element to which it is applied.

/***  Using element.append() ***/

document.body.append(myDiv); 
// myDiv will be final content on page

document.body.append("My String"); 
// text will be final content on page

myDiv.append(myArticle, "some text"); 
// myArticle and then the text will be last content within myDiv

element.prepend()

The prepend method works in exactly the same way as append, except it inserts whatever is passed into it as the first content within the element to which it is applied:

/***  Using element.prepend() ***/

document.body.prepend(mySpan); 
// mySpan will be first element on the page

document.body.prepend("My String"); 
// text will be first element on the page

myDiv.prepend(mySpan, "My String");
// mySpan and then text will appear as first content within myDiv

parentElement.insertBefore(newElement, existingElement)

If you want to insert an element somewhere in the middle of a list of elements (not first or last), you can use the insertBefore method.

insertBefore is applied to the parent element in which the list of elements are nested.

Pass in the new element as the first argument. And the element it should be inserted before as the second argument.

/***  Using element.insertBefore() ***/

myDiv.insertBefore(ToC, divBody);
// Inserts the element ToC before the element divBody within the myDiv element

myArticle.insertBefore(ad, midPara);
// Inserts the element ad before midPara within the myArticle element

Removing a DOM element βž–

element.remove()

You will be pleased to know that removing an element from the DOM is very straightforward:

Just apply the remove method to a DOM element and it will be removed from existence in the DOM.

But the element is still in memory in JavaScript after the removal. So you can still bring it back in.

/***  Using element.remove() ***/

myElement.remove();
// Removes myElement from the DOM

console.log(myElement);
// Returns element, even after removal from the DOM!

Setting the content inside elements ✏️

element.innerHTML

By applying the innerHTML method to an element, you can render string content to the DOM as HTML!

This is a powerful method, but be careful when using it in conjunction with user-generated content (e.g. form input) or data from a non-secure source.

Note that using innerHTML erases all existing content from within an element. If you want to get the existing HTML content before setting new content, apply innerHTML without setting any new content.

/***  Using innerHTML ***/

header.innerHTML = "<h1>My Title<h1>";
// Renders the string content as HTML inside the header element

document.body.innerHTML = `
<main>
   <h1>My page<h1>
   <div id="container">
      <article class="article">
         <h2>Article title</h2>
         <p>Article content</p>
      </article>
   </div>
</main>      
`
// Renders the template string to body of the page as HTML

element.innerText

A first approach to setting the content of an element to some text is to use the innerText method.

This preserves any string formatting. So, for example, a multi-line string will be rendered to the DOM across multiple lines:

/***  Using innerText ***/

myElement.innerText = `
My Address
My Road
My City
My Postcode
`
// Address is rendered to the DOM across multiple lines

element.textContent

The second approach to setting the text inside an element is to apply the textContent method.

This is not sensitive to formatting like innerText. This makes it ideal for extracting text from within an element while ignoring any element tags.

/***  Using textContent***/

myElement.innerHTML = `
<p>Here is some text.</p>
<p>It is wrapped in HTML tags.</p>
<p>These should be ignored when rendering this content.</p>
`
console.log(myElement.textContent); // ignores tags
// Here is some text.
// It is wrapped in HTML tags.
// These should be ignored when rendering this content

console.log(myElement.innerText); // prints text with tag formatting
// Here is some text.
//
// It is wrapped in HTML tags.
//
// These should be ignored when rendering this content

Editing element attributes πŸ“‹

element.setAttribute()

The attribute of any element can be set using the setAttribute method.

setAttribute can be applied to any element. As a first argument, it accepts the name of the element to be modified. If the attribute does not exist already, using setAttribute creates it. As a second argument, it accepts the new value of the attribute.

Note that the use of setAttribute will overwrite any existing value of an element. You can use element.getAttribute() to return the existing value of an element.

/***  Using setAttribute() ***/

myElement.setAttribute('id', 'article23'); // sets id to 'article23'

myElement.setAttribute('class', 'article mt-3 mb-3'); // sets class to 'article mt-3 mb-3'

myElement.setAttribute('myNewAttribute', 'text data'); // creates 'myNewAttribute' attribute on element containing 'text data'

element.classList.(add/remove/toggle)

To add, remove and toggle values on an element's class attribute apply the classList.add, classList.remove or classList.toggle to the element:

/***  Using classList.(add/remove/toggle)   ***/

myElement.classList.add('article'); // adds value 'article' to class attribute

myElement.classList.remove('article'); // removes value 'article' to class attribute 

myElement.classList.toggle= 'display'; // toggles value 'display' in class attribute

element.removeAttribute()

You can entirely remove an attribute from a DOM element by applying the removeAttribute element to it and passing in the attribute name:

/***  Using element.removeAttribute()   ***/

myElement.removeAttribute('class'); // removes the 'class' attribute

myElement.removeAttribute('linked-data'); // removes custom 'linked-data' attribute

Setting style properties πŸ–ŒοΈ

element.style

It is generally considered good practice to change the appearance of elements by changing class attribute values rather than setting style properties directly.

However, if you need to change the style of an element directly, these are stored in the style property.

To apply a style, write a valid CSS style in camel-case and set this to a valid CSS value.

/***  Using element.style   ***/

myElement.style.display = "none"; // hides element

myElement.style.fontSize = "1.2rem"; // sets element text size to 1.2rem

myElement.style.margin = "1rem"; // sets margin around element to 1rem

Summary

In this tutorial, we have covered the most important methods for manipulating the DOM using JavaScript.

Memorize this selection of techniques, and you'll be able to manipulate the DOM like a pro!

Related links