Last updated: Mar 5, 2024
Reading timeยท7 min
Use the querySelector
method to get an element by data attribute.
The querySelector
method returns the first element that matches the provided
selector or null
if no element matches the selector in the document.
Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div data-id="box1">Box 1</div> <span data-id="box2">Box 2</span> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
// โ Get the first element with data-id = `box1` const el1 = document.querySelector('[data-id="box1"]'); console.log(el1); // ๐๏ธ div // --------------------------------------------------- // โ Get the first element that has data-id attribute set const el2 = document.querySelector('[data-id]'); console.log(el2); // ๐๏ธ div // --------------------------------------------------- // โ Get all elements with data-id = `box1` const elements = document.querySelectorAll('[data-id="box1"]'); console.log(elements); // ๐๏ธ [div]
querySelectorAll
method. The method takes the same parameter as querySelector
.We used the
document.querySelector() method
to get the first element in the DOM that has a data-id
attribute equal to
box1
.
The second example shows how to get the first element that has the data-id
attribute set to any value.
const el2 = document.querySelector('[data-id]');
You can also narrow things down by looking for a specific type of element, e.g.
a div
that has a data attribute set to a certain value.
const el1 = document.querySelector('div[data-id="box1"]'); console.log(el1); // ๐๏ธ div
This example only selects div
elements that have a data-id
attribute set to
box1
.
querySelector
with querySelectorAll
.To get an element by partially matching a data attribute, use the
querySelector
method with a selector that matches a data attribute whose value
starts with, ends with or contains a specific string.
// โ get element where data-id starts with `bo` const el1 = document.querySelector('[data-id^="bo"]'); console.log(el1); // ๐๏ธ div // โ get element where data-id ends with `ox1` const el2 = document.querySelector('[data-id$="ox1"]'); console.log(el2); // ๐๏ธ div // โ get element where data-id contains `box` const el3 = document.querySelector('[data-id*="box"]'); console.log(el3); // ๐๏ธ div
querySelectorAll
method to get a collection of elements matching the selector.The first example selects the first DOM element that has a data-id
attribute,
whose value starts with bo
.
const el1 = document.querySelector('[data-id^="bo"]');
^
symbol, which has the same meaning when used with regular expressions.The second example selects the first DOM element that has a data-id
attribute
that ends with ox1
.
const el2 = document.querySelector('[data-id$="ox1"]');
The third example selects the first DOM element that has a data-id
attribute
that contains box
.
const el3 = document.querySelector('[data-id*="box"]');
box
could be located anywhere in the value of the data-id
attribute for the condition to be met.You could also prefix the selector with a specific type of element that you want to match to narrow down the results.
const el1 = document.querySelector('div[data-id^="bo"]');
The example selects a div
element that has a data-id
attribute that starts
with bo
.
You can use the querySelectorAll
method to get all elements by data attribute.
The querySelectorAll
method returns a NodeList
containing the elements that
match the specified selector.
Here is the HTML code for this example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div data-id="box1">Box 1</div> <div data-id="box2">Box 2</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
// โ Get all elements with `data-id` attribute const elements1 = document.querySelectorAll('[data-id]'); console.log(elements1); // ๐๏ธ [div, div] // โ Get only DIV elements with `data-id` attribute const elements2 = document.querySelectorAll('div[data-id]'); console.log(elements2); // ๐๏ธ [div, div] // โ Get only elements where data-id = box1 const elements3 = document.querySelectorAll(`[data-id="box1"]`); console.log(elements3); // ๐๏ธ [div]
We passed different selectors to the
document.querySelectorAll() method to
get a NodeList
containing the specific DOM elements.
Note that the querySelectorAll
method returns a NodeList
, not an array. If
you need to convert the response to an array, then pass it to the Array.from()
method.
const arr = Array.from(document.querySelectorAll('[data-id]'));
The first example shows how to get all DOM elements that have the data-id
attribute set.
const elements1 = document.querySelectorAll('[data-id]');
In the second example, we narrow things down to only div
elements that have
the data-id
attribute set.
const elements2 = document.querySelectorAll('div[data-id]');
If the DOM contained any span
or p
elements that have the data-id
attribute set, they wouldn't be included in the return value of the
querySelectorAll
method.
The third example selects elements that have the data-id
attribute set to
box1
.
const elements3 = document.querySelectorAll(`[data-id="box1"]`);
Note that the data-id
attribute has to be set to exactly box1
.
The querySelectorAll
method can also be used to get all DOM elements by
partial match of a data attribute.
// โ Get all where value of data-id starts with `bo` const elements1 = document.querySelectorAll('[data-id^="bo"]'); console.log(elements1); // ๐๏ธ [div, div] // โ Get all where value of data-id ends with `ox1` const elements2 = document.querySelectorAll('[data-id$="ox1"]'); console.log(elements2); // ๐๏ธ [div] // โ Get all where value of data-id contains with `box` const elements3 = document.querySelectorAll('[data-id*="box"]'); console.log(elements3); // ๐๏ธ [div, div]
The first example selects all DOM elements where the value of the data-id
attribute starts with bo
.
const elements1 = document.querySelectorAll('[data-id^="bo"]');
^
symbol, which has the same meaning when used in regular expressions.The second example selects all DOM elements where the value of the data-id
attribute ends with ox1
.
const elements2 = document.querySelectorAll('[data-id$="ox1"]');
The third example selects all DOM elements where the value of the data-id
attribute contains the string box
.
const elements3 = document.querySelectorAll('[data-id*="box"]');
box
could be located anywhere in the value of the data-id
attribute for the condition to be met.You could also prefix the selector with a specific type of element you want to match to narrow down the results.
const elements1 = document.querySelectorAll(`div[data-id^="bo"]`);
The example selects only div
elements that have a data-id
attribute set and
the attribute's value starts with bo
.
Use the dataset
property to get all of the data-* attributes of a DOM
element, e.g. el.dataset
.
The dataset
property provides read and write access to the custom data
attributes of the element. The property returns a Map
of strings that can be
converted to an object.
Here is the HTML
for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div id="box" data-bar="foo" data-id="example">Box 1</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const el = document.getElementById('box'); // ๐๏ธ DOMStringMap {bar: 'foo', id: 'example'} console.log(el.dataset); // โ Optionally convert it to Object const obj = {...el.dataset}; console.log(obj); // ๐๏ธ {bar: 'foo', id: 'example'}
We used the dataset property on the HTML element.
The property returns a read-only Map
of strings containing the custom data
attributes of the element.
The dataset
property itself is
read-only. To update a specific
property, we must access the nested property.
console.log(el.dataset.id); // ๐๏ธ "example" el.dataset.id = 'updated id'; console.log(el.dataset.id); // ๐๏ธ "updated id"
To update the data-id
attribute, we accessed the id
property on the
dataset
object and then assigned a new value to it.
If you want to convert the dataset
Map of strings to a native JavaScript
object, you can use the spread syntax (...).
// โ Optionally convert it to Object const obj = {...el.dataset}; console.log(obj); // ๐๏ธ {bar: 'foo', id: 'example'}
You could also implement a minimal replacement for the dataset
property.
const el = document.getElementById('box'); const dataAttrs = el.getAttributeNames().reduce((obj, name) => { if (name.startsWith('data-')) { return {...obj, [name.slice(name.indexOf('-') + 1)]: el.getAttribute(name)}; } return obj; }, {}); console.log(dataAttrs); // ๐๏ธ {bar: 'foo', id: 'example'}
We used the getAttributeNames()
method to get the names of all of the
attributes of the DOM element.
The next step is to use the reduce()
method to iterate over the array of
attribute names.
On each iteration, we check if the attribute's name starts with data-
and if
it does we assign the key/value mapping to the object.
This approach has many differences from the dataset
property and is only
supposed to be used if for some reason you don't have access to the dataset
property.
You can learn more about the related topics by checking out the following tutorials: