How to Select and Manipulate HTML Elements Using JavaScript

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

In this tutorial, you will learn how to select and manipulate HTML elements using JavaScript.

Table of Contents

You can skip to a specific section of this tutorial using the table of contents below:

Tutorial Configuration

As a quick recap, you will want to perform the following steps before proceeding through this tutorial:

  1. Download a fresh version of the JavaScript Fundamentals repository on GitHub
  2. Open the index.html file in a web browser (make sure that it renders as the actual webpage)
  3. Open the script.js file in your code editor

How to Select HTML Elements Using JavaScript

The most basic way that you can interact with an HTML element using JavaScript is by selecting an HTML element.

There are two methods available in JavaScript to do this - the querySelector method and the querySelectorAll method.

Both of these methods are contained in the document object that we referenced earlier. This means that when we call these methods in a JavaScript application, we write document.querySelector() and document.querySelectorAll().

Within the round brackets of each method, you need to specify what you're trying to select from the DOM. There are multiple ways of selecting HTML elements using JavaScript, including:

  • Selecting by the type of element (for example, selecting a <p> tag)
  • Selecting by the element's class (for example, selecting the class .red-text)
  • Selecting an element by passing in the element's ID (for example, selecting the ID #header)

Here are a few examples of how we could actual perform these examples using the querySelector method:

  • document.querySelector('p');
  • document.querySelector('.red-text');
  • document.querySelector('#header');

The Difference Between the querySelector and querySelectorAll Methods

You are probably wondering why JavaScript includes both the querySelector and querySelectorAll methods. Both methods are quite similar but have an important difference.

Namely, the querySelector method selects the first instance of an HTML element matching the parameter that you pass into the method. The querySelectorAll method selects every HTML element matching the parameter that you pass into the method.

Selecting Your First HTML Element From The DOM Using JavaScript

Let's select our first HTML element from the DOM using JavaScript! Specifically, let's select the very first HTML element contained within the <body> of the website, which is the following <h1> tag:

 <h1>This is my main header</h1>

Since we are only selecting a single element, it makes sense to use querySelector and not querySelectorAll. Let's select the <h1> tag and assign it to a variable called header.

We can do this by adding the following code to our script.js file:

const header = document.querySelector('h1');

You are probably curious about what exactly is contained within this header variable. The best ways to learn about a variable are to use the typeof keyword and the console.log method. We can run both of these within the console of our web browser:

typeof header;

//Returns "object"

console.log(header);

//Logs <h1>This is my main header</h1> to the console

As you can see, our header variable is an object (which means it can contain both attributes and method) and its value is the same as the <h1> tag in our HTML file index.html.

Selecting Multiple HTML Elements Using querySelectorAll

Let's now see an example of how to use the querySelectorAll method. As you can see by looking at our index.html file, there are multiple <p> tags contained within the document. We can select all of them using the querySelectorAll method like this:

const paragraphs = document.querySelectorAll('p');

If you log this paragraphs variable to the console, your web browser will print something like this:

NodeList(5) [p, p, p, p, p]

A JavaScript NodeList object is similar to a JavaScript array but doesn't contain all of the built-in methods that arrays have.

Said differently, this simply means that the JavaScript paragraphs variable is pointing to every <p> tag within the index.html file.

What if you later wanted to select a specific <p> tag from within this node list?

As an example, let's select the second <p> tag, which has a class of p2. The most straightforward way of doing this is to simply select an item that has a class of p2, like this:

secondParagraph = document.querySelector('.p2');

An alternative way of doing this is to chain together multiple querySelector statements. More specifically, you could add a second querySelector statement onto the paragraphs variable that we created earlier:

paragraphs.querySelector('.p2');

Using the querySelector method on an existing variable restricts the method's use to the elements contained within that variable, instead of the entire document (remember, the document is simply all of the code contained between the opening and closing <html> tags).

How to Add Text to an HTML Element Using JavaScript

There are a number of JavaScript methods that you can use to modify the HTML elements on your webpage. Perhaps the most important functionality you'll need is the ability to modify the text within an HTML element.

You can add text to the end of an HTML element using JavaScript's insertAdjacentText element. As an example, let's apply this method to the <h1> tag in our index.html file.

const header = document.querySelector('h1');

header.insertAdjacentText('beforeend', ' and JavaScript is awesome!');

The beforeend argument is important because it tells the method where to insert the text within the element. There are four options for this argument:

  • 'beforebegin': Before the element itself.
  • 'afterbegin': Just inside the element, before its first child.
  • 'beforeend': Just inside the element, after its last child.
  • 'afterend': After the element itself.

How to Add or Remove Classes From an HTML Element Using JavaScript

CSS classes provide a useful way to apply multiple styling parameters to an existing HTML element.

JavaScript makes it easy to add and remove CSS classes to HTML elements through an attribute called the classList.

The classList Attribute

This classList attribute is contained within each HTML element. We can add or remove classes to the HTML element by adding or removing that class to its classList attribute.

As an example, let's consider the <h2> tag within our index.html file, which has the class red-font applied to it:

secondHeader = document.querySelector('h2');

console.log(secondHeader.classList);

This will print something like this, which shows that the red-font class has been applied to the <h2> tag:

DOMTokenList ["red-font", value: "red-font"]

How To Add CSS Classes To An HTML Element Using JavaScript

Let's explore how to add a class to an existing HTML element using JavaScript.

Classes can be added to the classList attribute by calling the add method on it. As an example, here is how you could add the red-font class to our <h1> tag:

const header = document.querySelector('h1');

header.classList.add('red-font');

How To Remove CSS Classes From An HTML Element Using JavaScript

Removing CSS classes from an HTML element using JavaScript is similar to the technique we used to add classes. Instead of calling the add method on the classList attribute, we call the remove method.

Here's an example of how we could remove the red-font class (which just added in the last section) from our <h1> tag:

header.classList.remove('red-font');

How To Toggle CSS Classes On An HTML Element Using JavaScript

There are many situations in which you will want to toggle a CSS class on an HTML element. This means that you will add the class if it's not already there, and remove the class if it is already there.

We can do this using the toggle method on the classList attribute, like this:

header.classList.toggle('red-font');

A Note on Legacy Code

The querySelector and querySelectorAll methods have not always existed in the JavaScript codebase. Prior to their introduction, it was more difficult to select HTML elements on a webpage.

This means that if you are ever working on a legacy codebase, you may encounter instances of the old element selector methods. These methods include:

  • getElementById
  • getElementByClassName
  • getElementByName

and others. These methods are not useful now that querySelector and querySelectorAll exist, but it's important to know of their existence in case you encounter them in the future.

Final Thoughts

This tutorial taught you how to select and manipulate HTML elements using JavaScript.

Here is a brief summary of what you learned:

  • How to select HTML elements using JavaScript's querySelector and querySelectorAll method
  • The difference between the querySelector and querySelectorAll methods
  • How to add text to an existing HTML element with JavaScript using the insertAdjacentText method
  • How to add, remove, and toggle CSS classes on specific HTML elements using JavaScript methods