Change parent block background when child input is checked(vanilla js)

I am new to the world of coding, and would be very grateful for an advise or any idea. I was wondering if it is possible to change color of current parent block background(.checkbox-container), when child input is checked. And the main problem is that I have multiple blocks with inputs, and require to change background color only to current block, not to all? As I understood there is no pure css solution without mark-up change, but this is not my case. Could someone please give any idea how that could be done in vanilla js?

Here is the link to fiddle:

https://jsfiddle.net/william_eduards/r4jxvuz5/4/

and visual code example here:

.checkbox-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: nowrap;
  background: #E8EBF0;
  border: 1px solid #E8EBF0;
  transition: background .3s ease-in-out;
  margin-bottom: 8px;
  border-radius: 4px;
}
<div class="dimensional-container checkbox-container">
  <input type="checkbox" name="snapchat" class="checkbox-container__snapchat" id="snapchat">
  <label for="snapchat">snapchat</label>
</div>
<div class="dimensional-container checkbox-container">
  <input type="checkbox" name="facebook" class="checkbox-container__facebook" id="facebook">
  <label for="facebook">Facebook</label>
</div>
<div class="dimensional-container checkbox-container">
  <input type="checkbox" name="hangouts" class="checkbox-container__hangouts" id="hangouts">
  <label for="hangouts">hangouts</label>
</div>

Answer

  • Find all input using querySelectorAll.
  • Loop over all input and addEventListener
  • check if the elment is checked or not using e.target.checked, If it is checked change its parent e.target.parentElement background style.

I’ve used red, you can select color on your own.

const allInputs = document.querySelectorAll("input");

allInputs.forEach(input => {
  input.addEventListener("click", e => {
    if (e.target.checked) {
      e.target.parentElement.style.background = "#ff0000";
    } else {
      e.target.parentElement.style.background = "#E8EBF0";
    }
  })
})
.checkbox-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: nowrap;
  background: #E8EBF0;
  border: 1px solid #E8EBF0;
  transition: background .3s ease-in-out;
  margin-bottom: 8px;
  border-radius: 4px;
}
<div class="dimensional-container checkbox-container">
  <input type="checkbox" name="snapchat" class="checkbox-container__snapchat" id="snapchat">
  <label for="snapchat">snapchat</label>
</div>
<div class="dimensional-container checkbox-container">
  <input type="checkbox" name="facebook" class="checkbox-container__facebook" id="facebook">
  <label for="facebook">Facebook</label>
</div>
<div class="dimensional-container checkbox-container">
  <input type="checkbox" name="hangouts" class="checkbox-container__hangouts" id="hangouts">
  <label for="hangouts">hangouts</label>
</div>