Manipulating the DOM with JavaScript 101
Mai G.
Posted on May 14, 2023
What is DOM?
DOM stands for Document Object Model, a programming interface that allows web developers to manipulate HTML and XML files. Using scripting languages such as JavaScript, developers can access and modify the structure, style and content of the DOM to generate dynamic and interactive web pages. In this post, we'll go over the basic steps to manipulate the DOM with JavaScript.
Access DOM Elements
First and foremost, we need to access the element in the DOM that we need to modify. This can be done in a number of ways, but my favorite way is by the method of .querySelector()
. It would be best to assign that element to a variable. The syntax looks like below:
- Access element based on id
const idName = document.querySelector('#idName');
- Access element based on a class
const className = document.querySelector('.className');
- Access element based on a tag
const h2 = document.querySelector('h2');
To access all elements sharing the same class or tag, use .querySelectorAll()
Access all h2 elements
const h2 = document.querySelectorAll('h2');
Adding and Removing HTML Elements
Adding or removing HTML elements is one of the most common ways to manipulate the DOM with JavaScript. Before adding an element, we first would need to create it. To create a new element, we use the .createElement()
method:
const newDiv = document.createElement('div');
After that, we would want to use .append()
to add the new div
element to a another element:
For example, we would like to add it to the end of the body
element, we would first need to grab the body element
const body = document.querySelector('body');
body.appendChild(div);
To remove an element from the DOM, we can use the .remove()
method.Of course, we need to start by retrieve the element we would like to remove:
const example = document.querySelector('#example');
example.remove();
Modifying HTML Element Attributes
It is also possible to modify HTML element attributes such as class
, id
, src
, and href
using JavaScript. See examples below:
- Retrieve the image we want to update
const image = document.querySelector('#imageID');
image.src = "new URL";
- Add a new class to an element
const element = document.querySelector('#elementID');
element.classList.add('newClass');
- Remove a class from an element
element.classList.remove('className');
As you can see, DOM manipulation with JavaScript is a powerful tool for creating dynamic and interactive user interfaces. Once you are proficient in manipulating the DOM with JavaScript, you can open up a world of possibilities for web development projects. In this post, we only cover the most basic DOM manipulation methods. If you're interested in learning more, head to MDN for more detailed documents.
Happy coding!
Posted on May 14, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.