Summarizing the Question and Solution
Below you can see two onClickHandler that logs out the event.target.
Expected: retrieve the parent node of the leaf nodes (children nodes without children nodes or innermost HTML element).
Actual: retrieved the leaf nodes.
Fix: change event.target
to event.target.parentNode
.
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
function onClickHandler(event) {
console.log(event.target); // THE FIX: change this to event.target.parentNode
}
return (
<>
<div className="one" onClick={onClickHandler}>
<div className="two"></div>
</div>
<div className="one" onClick={onClickHandler}>
<div className="two">
<img className="three" />
</div>
</div>
</>
);
}
Here’s a sandbox of a problem I’ve run into. I’m using React:
<div className="1" onClick={onClickHandler}>
<div className="2">
<img className="3">
</div>
</div>
In scenarioA, img
wasn’t present & onClickHandler
‘s e.target
referenced element 2
. I believe this is because:
- ‘1’ & ‘2’ overlapped each other – when you clicked on one you clicked on the other.
- Like
e.currentTarget
, e.target
will reference the ‘highest’ element you click on that has a ‘click’ handler – with an exception: if the element has a descendant that is also clicked on when you click, it’ll reference the lowest descendant.
The problem: in scenarioB, img
has been added & now e.target
refers to img
. I need to refer to element 1
& 2
and intend to do this with the event handler staying on ‘1’.
Solutions:
-
Somehow, in onClickHandler
get it to see ‘2’.
-
Refactor img
to be like ‘2’. In my project, I think all this’d involve is making img
have all the html attributes ‘2’ has. However, I know having the attributes on ‘2’ works – and even though I can’t think of a way why this solution would break, I’m hesitant – especially if solution#1 works.
Thanks @pilchard I’ve updated to the question to say one of the conditions is the event handler must stay on element ‘1’. I want to reference elements