Search code examples
javascripteventsonclick

How to get target element with onclick() javascript


I was trying to get the target element using onclick() function and just noticed that it is not possible using e.target though it was possible with deprecated event.target (still giving result). Ths can still be done using addEventlistener, but is there a way to do it using onclick() function? below is my code:

function check(e){
  let targetElem = e.target     //code working with event.target
  console.log({targetElem})
}
<div class="target-div">
    <div class="first-div" onclick="check(this)">
        hello everybody
    </div>
</div>
<div class="target-div">
    <div class="second_div" onclick="check(this)">
        hello everybody
    </div>
</div>

always get undefined for console.log(targetElem), tried removing 'this', then gives an error thanks for your explanation


Solution

  • this refers to the element itself, so if that's what you're looking for then you can reference it directly:

    function check(e) {
      console.log({ targetElem: e });
    }
    <div class="target-div">
        <div class="first-div" onclick="check(this)">
            hello everybody
        </div>
    </div>
    <div class="target-div">
        <div class="second_div" onclick="check(this)">
            hello everybody
        </div>
    </div>

    Otherwise, if you do want the entire event object, pass event instead of this:

    function check(e) {
      let targetElem = e.target;
      console.log({ targetElem });
    }
    <div class="target-div">
        <div class="first-div" onclick="check(event)">
            hello everybody
        </div>
    </div>
    <div class="target-div">
        <div class="second_div" onclick="check(event)">
            hello everybody
        </div>
    </div>