In the following code, how to get the text inside div
on the onClick
event?
import React from "react";
import * as ReactDOM from "react-dom/client";
class TestTag extends React.Component {
render() {
return <div onClick={() => console.log(this.innerHTML)}> Hello world </div>;
}
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<TestTag />);
CodePudding user response:
You could pass the event
to your onClick
handler and get the innterHTML/innerText,
<div onClick={(e) => console.log(e.target.innerHTML)}> Hello world </div>;
CodePudding user response:
I'm not sure how committed you are to using a "this", but you can easily get the text this way:
import React from "react";
import * as ReactDOM from "react-dom/client";
class TestTag extends React.Component {
render() {
return <div id = "maindiv" onClick={() => console.log(document.getElementById("maindiv").innerHTML)}> Hello world </div>;
}
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<TestTag />);