Get an HTML element by class in JavaScript

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

<figure class="kg-card kg-embed-card"><iframe class="cpembediframe" frameborder="0" height="300" id="cpembedVwadVEw" scrolling="no" src="https://codepen.io/imkmf/embed/preview/VwadVEw?height=300&slug-hash=VwadVEw&default-tabs=html,result&host=https://codepen.io" style="width: 100%; overflow: hidden;" title="JavaScript: Get Element by Class"></iframe></figure>