Bytesized

Bytesized • Resources, tutorials, and newsletters for software developers.

JavaScript: Get element by class

Use vanilla JavaScript's querySelector and querySelectorAll methods to target DOM elements on an HTML page.

JavaScript: Get element by class

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

Enjoying these posts? Subscribe for more

Subscribe to be notified of new content and support Bytesized! You'll be a part of the community helping keep this site independent and ad-free.

You've successfully subscribed to Bytesized
Great! Next, complete checkout for full access to Bytesized
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.