how to get an element by data attribute in javascript

We can use the querySelectorAll method to select all elements that have a specific data attribute. Here's an example:

index.tsx
const elements = document.querySelectorAll('[data-attribute-name="value"]');
77 chars
2 lines

This will find all the elements that have a data-attribute-name attribute with a value of value.

Alternatively, we can use the getElementsByAttributeValue method if we want to select elements by a data attribute value without using a CSS selector. Here's an example:

index.tsx
const elements = document.getElementsByAttributeValue('data-attribute-name', 'value');
87 chars
2 lines

This will find all the elements that have a data-attribute-name attribute with a value of value.

If we have an element with a known id, we can also use getElementById:

index.tsx
const element = document.querySelector('#element-id');
const attributeValue = element.getAttribute('data-attribute-name');
123 chars
3 lines

This finds the element with id equal to 'element-id' and then obtains the value of its data-attribute-name attribute.

gistlibby LogSnag