1

I have a div that encompasses a checkbox, I want to only have the querySelector target the child element of THIS clicked element. As of right now, if I click the one below, it will trigger the click on the checkbox above. How can I do this?

HTML

<div class="message-checkbox-container" style="height: 47px;" onclick="triggerCheck()">
     <input class="message-checkbox" type="checkbox">
</div>
<div class="message-checkbox-container" style="height: 47px;" onclick="triggerCheck()">
     <input class="message-checkbox" type="checkbox">
</div>

Javascript

function triggerCheck(){
document.querySelector('.message-checkbox').click();
}

1 Answers1

1

Attach the event listener using addEventListener instead - inline handlers have way too many problems to be worth using in a modern codebase. To attach the listener, select .message-checkbox-container elements, and you can use the closure over each element to refer to its first child, the input, inside the listener:

for (const container of document.querySelectorAll('.message-checkbox-container')) {
  container.addEventListener('click', () => {
    container.children[0].click();
  });
}
<div class="message-checkbox-container" style="height: 47px;">container
     <input class="message-checkbox" type="checkbox">
</div>
<div class="message-checkbox-container" style="height: 47px;">container
     <input class="message-checkbox" type="checkbox">
</div>

Not that you should do this, but you can reference this inside an inline handler to get a reference to the element the handler is attached to - you can pass that to the function and have the function call querySelector (or .children[0]) on it:

function triggerCheck(elm) {
  elm.querySelector('.message-checkbox').click();
}
<div class="message-checkbox-container" style="height: 47px;" onclick="triggerCheck(this)">container
  <input class="message-checkbox" type="checkbox">
</div>
<div class="message-checkbox-container" style="height: 47px;" onclick="triggerCheck(this)">container
  <input class="message-checkbox" type="checkbox">
</div>

You might consider using a <label> instead of a <div>, that way the checkbox will be toggled automatically when the label is clicked, no Javascript necessary:

.message-checkbox-container {
  display: block;
  cursor: pointer;
}
<label class="message-checkbox-container" style="height: 47px;">container
  <input class="message-checkbox" type="checkbox">
</label>
<label class="message-checkbox-container" style="height: 47px;">container
  <input class="message-checkbox" type="checkbox">
</label>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320