- Instant help with your JavaScript coding problems

Get elements by data attribute in JavaScript

Question:
How to get elements by data attribute in JavaScript?
Answer:
const itemList = document.querySelectorAll('li[data-id]');
Description:

In the querySelectorAll method, the selector parameter is a string containing one or more selectors to match against. This string must be a valid CSS selector string. This also means you can use the data attribute to collect the required elements.

For example, to get all li element that has a data-id attribute you can use the query:

const listItems = document.querySelectorAll('li[data-id]');

 

Reference:
querySelectorAll
Returns a static NodeList representing a list of the document's elements that match the specified group of selectors.
JavaScript:
querySelectorAll(selectors)
TypeScript:
querySelectorAll(selectors: K): NodeListOf;
Examples:
const items = document.querySelectorAll(".highlighted > p");
Share "How to get elements by data attribute in JavaScript?"