Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get as e.target the exact element at which onClick is specified?

I have a React Component and give it onClick event handler:

function Item(props) {
  return <li onClick={props.onClick}>{props.children}</li>
}

Then I use the Component like this:

<Item onClick={ function(e) {console.log(e.target)} }>
  <span>This element is returned as e.target if clicked on it!</span>
</Item>

When I click on the text, the span element is logged as target and when it is clicked outside given span, li element is logged as target.

The problem is:
If there is a lot of child elements inside li element, and id or name are have to be gotten, it becomes a "hacky" task...

The question is:
Is it possible to get inside a handler function as e.target the exact element at which onClick is specified (not it's children; in this case li)?

PS. No jQuery for solution if possible.

like image 838
olegzhermal Avatar asked Mar 29 '17 09:03

olegzhermal


People also ask

How do you get the ID of an element in JavaScript from a clicked?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

What is E target value in JavaScript?

Thus e. target. value is the value property of some DOM element, in this case that means the text entered in the search input.

How do you know which element is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.


1 Answers

event.target will always give you the element, which dispatched the event. In order to get the element who's listener is currently processed, you have to use event.currentTarget.

This should help: https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets

Here is a simple example to illustrated your issue:

const Inner = () => <div className="inner">Inner</div>

const Outer = () => {
  const clickHandler = e => {
    console.log('target:', e.target.getAttribute('class'));
    console.log('currentTarget:', e.currentTarget.getAttribute('class'));
  };

  return (<div className="outer" onClick={clickHandler}><Inner /></div>);
};

ReactDOM.render(<Outer/>, document.getElementById('app'));
.outer {
  background: rosybrown;
  padding: 40px;
}

.inner {
  background: cornsilk;
  padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>
like image 152
Sebastian Sebald Avatar answered Oct 03 '22 00:10

Sebastian Sebald