Solution 1 :

You can get the for attribute by using e.srcElement.htmlFor or e.target.htmlFor.

P.S. – for is not a tag, it is an attribute. You can get value of any attribute by using getAttribute().

Solution 2 :

Most probably, your lable will be the adjacent previous sibling of the input element. In this case, you can use previousElementSibling.id to get the id of the lable. Below is a snippet explaining the same –

document.addEventListener('mousedown', function(e) {
  e = e || window.event;  
  //Check if we have clicked on an input -
  if(e.target.outerHTML.includes("input")){
    alert(e.target.previousElementSibling.id);
  }
}, false);
<lable for="check" id="lable">Check1</lable>
<input type="checkbox" id="check" name="check">
<br>
<br>
<lable for="check2" id="lable2">Check2</lable>
<input type="checkbox" id="check2" name="check2">

In this way, you can implement the same solutions with multiple inputs.

Problem :

I try to track the clicks on my website. Therefore I use e.target.id. When clicking on a label with for=”mycheckbox” I will get the id of the label, not the checkbox. How can I get the for tag?

document.addEventListener('mousedown', function(e) {
  e = e || window.event;
  alert("checkbox with id: " + e.target.id.toString() + " checked"); //doesn't work with labels
, false);

Regards

Comments

Comment posted by Oskar Zanota

Shouldn’t it be e.target.getAttribute(“for”) ?

Comment posted by John Doe

That’s right, vs code didn’t liked to show me this option for e.target.

Comment posted by John Doe

Still wondering why vs code doesn’t recognize getAttribute with event.target. Heard that it is not a html element. Anyway, works!

By