select an element by attribute in javascript

To select elements by attribute in JavaScript, you can use the querySelectorAll method and pass in a selector that uses the attribute selector syntax. The syntax is as follows:

index.tsx
document.querySelectorAll('[attributeName="value"]');
54 chars
2 lines

For example, to select all elements with a data-role attribute that has a value of "button", you can use the following code:

index.tsx
const buttons = document.querySelectorAll('[data-role="button"]');
67 chars
2 lines

This will return a NodeList of all elements that match the selector. You can then loop through this list or access individual elements by index as needed.

If you only need to select a single element, you can use the querySelector method with the same syntax:

index.tsx
const button = document.querySelector('[data-role="button"]');
63 chars
2 lines

gistlibby LogSnag