Solution 1 :

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>
    </>
  );
}

Problem :

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. ‘1’ & ‘2’ overlapped each other – when you clicked on one you clicked on the other.
  2. 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:

  1. Somehow, in onClickHandler get it to see ‘2’.

  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.


Comments

Comment posted by docs

Just attach the listener to 2 and use .currentTarget which

Comment posted by tonitone120

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

Comment posted by pilchard

is two always the first child? then

Comment posted by ValeriF21

How about using e.target.parentNode ? Possible ? @tonitone120

By