Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading