Home > Blockchain >  Get dataset of parent, while clicking on child
Get dataset of parent, while clicking on child

Time:12-14

I have the following code, in which I have a button with data attribute and div inside of it, I want to get the dataset of button, no matter how deep is the target inside of a child.

export default function App() {
  const handler = (e) => {
    console.log(e.target.dataset.id);
  };
  return (
    <div className="App">
      <button
        data-id="myDataId"
        onClick={handler}
        style={{ 
          height: 200, 
          width: 200, 
          backgroundColor: "green" 
        }}
      >
        Bruh
        <div
          style={{
            height: 100,
            width: 100,
            backgroundColor: "red"
          }}
        />
      </button>
    </div>
  );
}

In this example, my console gives undefined when I click inside of the div, but if Iclick to button, it gives my data attribute.

I tried to use event.path, but it didn't give any results.

Is there any generic way to get the dataset of my button?.

Here is the fully working example: https://codesandbox.io/s/lucid-breeze-e1lh2?file=/src/App.js:23-535

CodePudding user response:

Use parentNode.getAttribute()

export default function App() {
  const handler = (e) => {
    console.log(e.target.parentNode.getAttribute("data-id"));
  };
  return (
    <div className="App">
      <button
        data-id="myDataId"
        onClick={handler}
        style={{ 
          height: 200, 
          width: 200, 
          backgroundColor: "green" 
        }}
      >
        Bruh
        <div
          style={{
            height: 100,
            width: 100,
            backgroundColor: "red"
          }}
        />
      </button>
    </div>
  );
}

CodePudding user response:

You can use the parentElement property of the target.

If you don't know how deep the target might be, you can seek it like so:

const handler = (e) => {
  let target = e.target
  while (!('id' in target.dataset)) target = target.parentElement

  console.log(target.dataset.id)
}
  • Related