What's the best way to use javascript get data attribute from an element? or How do you properly use

22 Replies, 1437 Views

For edge cases, like dynamic elements, combine `getAttribute()` with event delegation.

Example:

```
document.addEventListener('click', (e) => {
const value = e.target.getAttribute('data-action');
if (value) { /* do stuff */ }
});
```

Works like a charm!
If you’re using frameworks like React or Vue, they handle data attributes differently.

In React, you’d use `dataset` but with JSX syntax like `data-thing={value}`.

Vue has `v-bind:data-thing`—so framework context matters!



Users browsing this thread: 1 Guest(s)