-2

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>

4
  • Why are you spamming questions! Commented Mar 29, 2021 at 19:05
  • Because I was asked to post a new question as there wasn't a CSS solution as per a previous answer - so I asked the equivalent about a javascript solution. Commented Mar 29, 2021 at 19:07
  • Have you tried researching ones, This is a very basic question and if you would have even search your own question title, you would have got your answer😟 Commented Mar 29, 2021 at 19:11
  • Does this answer your question? Change styles when checking checkbox with JavaScript Commented Mar 29, 2021 at 19:11

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

-1

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>

2 Comments

OP did not ask to change the HTML layout!
Yeh this would be the ideal solution... but unfortunately I am unable to change the HTML layout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.