reactjsdrag-and-drop

get id of parent from a child


I'm adding drag and drop to a child component and I want to get the id of the parent component in the dragstart event so the drag operation will know where the component originated from. Is there a way to do that with the DOM?


Solution

  • Just check the parent node of the target of the event.

    event.target.parentNode.id

    Easy example with click event HTML:

    <p id="a">
      <button id="button">my parrent has ID "a"</button>
    </p>
    

    JS:

    document.getElementById("button").addEventListener("click", (event) => {
        console.log(event.target.parentNode.id) // this should be "a"
    })