How to toggle a checkbox inside of a div when clicking on the div using JavaScript?

Sometimes, we want to toggle a checkbox inside of a div when clicking on the div using JavaScript.

In this article, we’ll look at how to toggle a checkbox inside of a div when clicking on the div using JavaScript.

How to toggle a checkbox inside of a div when clicking on the div using JavaScript?

To toggle a checkbox inside of a div when clicking on the div using JavaScript, we can add a click handler to the div.

For instance, we write:

<div>
  <input type='checkbox'>
  toggle
</div>

to add a div with a checkbox input inside.

Then we write:

const div = document.querySelector('div')
div.onclick = (e) => {
  const input = e.target.querySelector('input')
  input.checked = !input.checked
}

to select the div with querySelector.

Next, we set div.onclick to a function that selects the input inside the div with e.target.querySelector.

e.target is the div.

Then we set the checked property to the negation of the current checked value to toggle the checkbox.

Conclusion

To toggle a checkbox inside of a div when clicking on the div using JavaScript, we can add a click handler to the div.