I am looking to change the style of the parent label when the checkbox is checked. I realise this can't feasibly be done with CSS, is this possible with Javascript?
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
I am looking to change the style of the parent label when the checkbox is checked. I realise this can't feasibly be done with CSS, is this possible with Javascript?
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
Yes, here's an example:
const container = document.querySelector('#cont');
const checkbox = document.querySelector('input');
checkbox.addEventListener('change', () => {
if (checkbox.checked) {
container.style.background = 'red'
} else {
container.style.background = 'white'
}
})
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
Your question is a bit unclear. If you have just a single parent element and checkbox like your code suggests, then it's straightforward. You can define the new styles you want a class(let's say a class called new-style) inside your stylesheet, then add a listener function inside your js script to trigger when the checkbox is clicked. The listener function will basically insert the class into the parent if it doesn't have it or remove it if it does. Something like this.
<script>
let checkbox = document.querySelector('input[type="checkbox"]');
checkbox.onclick = function() {
let parent = document.querySelector('#cont')
parent.classList.toggle('new-style');
}
</script>
Have you tried it this way? You can use css :checked property for this.
input:checked + label {
color: red;
}
<input id="name" type="checkbox">
<label for="name" id="cont">
label
</label>