-1

I have an event listener for some checkboxes:

$('.table-sticky-container').on('click', 'label', function() {
  console.log(this);
})

This logs: < label id="checkbox,0">...</label

How do I access this id? I would like it to console "checkbox,0". I'm not sure about the syntax. I tried this.id, this('label[id]]') and bunch of other stuff. Anybody know? Thank you.

  • `this.getAttribute('id')` should work https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute – GrafiCode May 20 '22 at 17:55
  • 1
    @GrafiCode `getAttribute()` isn't wrong, but it's unnecessary. See my answer below. – Scott Marcus May 20 '22 at 17:56
  • @ScottMarcus you're right. Since OP is using jQuery, even `$(this).attr('id')` would work, but your solution is the most performant. – GrafiCode May 20 '22 at 17:59

1 Answers1

-1

By accessing the id property of this:

$('#foo').on('click', function() {
  console.log(this.id);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<lable id="foo">Test</label>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71