Skip to main content

How to Get an Element by a Data Attribute in JavaScript

Data attributes (data-*) are a powerful feature in HTML for storing custom data on an element. A common and efficient way to select these elements in JavaScript is by using CSS attribute selectors. This is the standard method for querying the DOM based on the presence, exact value, or partial value of any attribute.

This guide will teach you how to use querySelector() and querySelectorAll() with various attribute selectors to find elements based on their data-* attributes, making your DOM selection precise and powerful.

The Core Method: CSS Attribute Selectors

The document.querySelector() and document.querySelectorAll() methods are the definitive tools for selecting DOM elements. They work with any valid CSS selector, including attribute selectors, which use square brackets ([...]).

HTML for Examples:

<div data-id="box-1">Box 1</div>
<div data-id="box-2" data-status="active">Box 2</div>
<div data-id="item-3" data-status="inactive">Box 3</div>

Selecting by an Exact Data Attribute Value

This is the most common use case. You want to find an element where a data attribute has a specific, known value.

Syntax: [data-attribute-name="value"]

Solution:

// Get the first element with a data-id of "box-1"
const el1 = document.querySelector('[data-id="box-1"]');
console.log(el1.textContent); // Output: "Box 1"

// You can also check for the mere presence of an attribute
const firstElWithDataId = document.querySelector('[data-id]');
console.log(firstElWithDataId.textContent); // Output: "Box 1"
note

This is a highly efficient way to select elements without relying on IDs or classes.

Selecting by a Partial Match of a Data Attribute

CSS attribute selectors also support powerful partial matching, similar to regular expressions.

Find an element where the data-id starts with "box-"

Use the ^= operator.

const el = document.querySelector('[data-id^="box-"]');
console.log(el.textContent); // Output: "Box 1"

Find an element where the data-id ends with "-2"

Use the $= operator.

const el = document.querySelector('[data-id$="-2"]');
console.log(el.textContent); // Output: "Box 2"

Find an element where the data-id contains "item"

Use the *= operator.

const el = document.querySelector('[data-id*="item"]');
console.log(el.textContent); // Output: "Box 3"

How to Get All Matching Elements

querySelector() only ever returns the first matching element. To get all elements that match a selector, you must use document.querySelectorAll(). This returns a NodeList containing all the matches.

Solution:

// Get ALL elements that have a data-status attribute
const allStatusElements = document.querySelectorAll('[data-status]');
console.log(allStatusElements.length); // Output: 2

// You can iterate over the NodeList with forEach
allStatusElements.forEach(el => {
console.log(el.dataset.status); // Prints 'active', then 'inactive'
});

// Get ALL elements whose data-id starts with "box"
const allBoxes = document.querySelectorAll('[data-id^="box"]');
console.log(allBoxes.length); // Output: 2

Bonus: Accessing All Data Attributes on an Element

If you already have a reference to an element and want to get all of its data-* attributes, you can use the element.dataset property. This returns a DOMStringMap, which is an object-like structure containing all the element's data attributes.

Solution:

<div id="my-element" data-user-id="123" data-user-role="admin">...</div>
const el = document.getElementById('my-element');

// The .dataset property gives you an object of all data attributes
const allDataAttributes = el.dataset;
console.log(allDataAttributes);
// Output: DOMStringMap { userId: "123", userRole: "admin" }

// You can access individual attributes as properties
console.log(allDataAttributes.userId); // Output: "123"
note

Attribute names are converted to camelCase in the dataset object (e.g., data-user-role becomes userRole).

Conclusion

CSS attribute selectors provide a powerful and declarative way to find elements by their data-* attributes.

  • To find the first matching element, use document.querySelector().
  • To find all matching elements, use document.querySelectorAll().
  • Use the attribute selector syntax for precise matching:
    • [data-id="value"] for an exact match.
    • [data-id^="value"] for a "starts with" match.
    • [data-id$="value"] for an "ends with" match.
    • [data-id*="value"] for a "contains" match.
  • To access all data attributes on an element you already have, use the element.dataset property.