Scenario: When the user clicks on it, the data should be passed into someFunction()
.
<span id="someid" onClick={() => someFunction()} data-video-page="some data" />`
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.
CodePudding user response:
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>
);
}
CodePudding user response:
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>
CodePudding user response:
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');