find element by data-id in javascript

To find an element by its data-id attribute in JavaScript, you can use the querySelector method along with the attribute selector.

Here's an example:

index.tsx
const element = document.querySelector('[data-id="your-data-id-value"]');
74 chars
2 lines

In the above code, the querySelector method takes an attribute selector [data-id="your-data-id-value"] as an argument. It searches and returns the first element that matches the data-id attribute with the specified value.

You can replace 'your-data-id-value' with the actual value you want to find. Make sure to include the square brackets and quotation marks around the attribute selector.

If there is no matching element found, the querySelector method will return null.

Once you have obtained the element, you can perform any required operations on it, such as accessing its properties or modifying its content.

index.tsx
if (element) {
   // Do something with the element
   console.log(element.textContent);
} else {
   console.log('Element not found');
}
136 chars
7 lines

Remember, the querySelector method only returns the first matching element. If you want to find multiple elements with the same data-id attribute, you can use the querySelectorAll method instead.

index.tsx
const elements = document.querySelectorAll('[data-id="your-data-id-value"]');
elements.forEach(element => {
   // Do something with each element
   console.log(element.textContent);
});
186 chars
6 lines

I hope this helps! Let me know if you have any further questions.

related categories

gistlibby LogSnag