0

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.

3 Answers 3

2

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>
  );
}


Sign up to request clarification or add additional context in comments.

Comments

0

A working snippet

const someFunction = console.log;

function App() {
    return (
        <span id="someid" 
          onClick={(e) => {
            const videoPage = event.target.dataset['videoPage'];
            someFunction(videoPage)
          }} 
          data-video-page="some data" 
          className="dot" 
        >
        click me
        </span>
     )
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Comments

0

The data* attribute can be accessed using the getAttribute() method.

Example 1:

var data = document.getAttribute('data*');

Example 2:

var element = document.querySelector('div');
var data = element.getAttribute('data');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.