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>