Get an HTML element by class in JavaScript

#archive

This post is out of date

This post has been migrated from my old blog. It may have broken links, or missing content.

You can target an HTML element with JavaScript by using document.querySelector. This API is similar to jQuery’s basic $ function.

Using document.querySelector

You can use document.querySelector to target an element, such as an h1 with a class of title:

const title = document.querySelector(".title")

Once you’ve captured that element with a variable, you can query and interact with the HTMLElement (see MDN for the docs) in a number of ways:

title.className // Get the CSS class
title.dataset // Interact with any data attributes on the element
title.innerText // Get the text of the element
title.style // Query the CSS styles for the element

Selecting multiple elements

If you need to select multiple elements, you can use document.querySelectorAll to get an array of elements:

const titles = document.querySelectorAll(".title")
console.log(titles.length) // 2

querySelectorAll returns a NodeList, but you can still iterate through it using forEach, as seen below:

const titles = document.querySelectorAll(".title")
titles.forEach(title => console.log(title.innerText))

Example Codepen