javascripthtmlreactjs

How to access the data from data* attribute using JavaScript?


Scenario: When the user clicks on it, the data should be passed into someFunction().

<span id="someid" onClick={() => someFunction()} data-video-page="some data" class="dot" />`

I tried using getAttributes(), querySelector() methods until now to get the data from data attributes. But one of them are working, in fact they are returning none.


Solution

  • There is a React.js tag in your question, so I'll assume that this is for using data-set in React.js.

    For React.js, this is how data-set can be used if you want to pass the data to some function on a click event. You can also visit the live demo here: stackblitz

    const handleClick = (event) => {
    
      // Your data is stored in event.currentTarget.dataset
      // Here we get the data by destructuring it
      // The name video-page need to change to videoPage for JS rules
    
      const { videoPage } = event.currentTarget.dataset;
      console.log(videoPage);
    
      // Result printed: "your data"
      // You can also run someFunction(videoPage) here
    };
    
    export default function App() {
      return (
        <button data-video-page="your data" onClick={handleClick}>
          TEST
        </button>
      );
    }