How can I get multiple elements to work with JavaScript?

Viewed 43

So when I click the checkbox, the background colour changes. I want this function to work for all checkboxes, but it is currently only working for the first one.

function obtained() {
  var obt = document.getElementsByClassName("obtained")[0];
  var col = document.getElementsByClassName("entry")[0];
  if (obt.checked == true) {
    col.style.backgroundColor = "#2ab320";
  } else {
    col.style.backgroundColor = "#d3d5db";
  }
}
<div class="entry">
  <img class="class-name" src="image1.png">
  <b>title1</b><br>content1
  <input 
    type="checkbox" 
    class="obtained" 
    onclick="obtained()" 
    name="obtained"
  >
</div><hr>
<div class="entry">
  <img class="class-name" src="image2.png">
  <b>title2</b><br>content2
  <input 
    type="checkbox" 
    class="obtained" 
    onclick="obtained()" 
    name="obtained"
  />
</div><hr>
<div class="entry">
  <img class="class-name" src="image3.png">
  <b>title3</b><br>content3
  <input 
    type="checkbox" 
    class="obtained" 
    onclick="obtained()" 
    name="obtained"
  />
</div><hr>

2 Answers

In cases like this one you should declare a helper function:

function makeTogglable(element) {
  const obt = element.querySelector(".obtained");
  obt.addEventListener("click", () => {
    if(obt.checked == true) {
      element.style.backgroundColor = "#2ab320";
    } else {
      element.style.backgroundColor = "#d3d5db";
    }
  });
}

Then you can apply it your HTML elements, for example:

document.querySelectorAll('.entry').forEach(e => makeTogglable(e));

Edit: forgot about listeners

You could pass an instance of the checkbox to the function like so:

function obtained(element) {
  var col = element.parentElement;
  if (element.checked == true) {
    col.style.backgroundColor = "#2ab320";
  } else {
    col.style.backgroundColor = "#d3d5db";
  }
}
<div class="entry">
  <img class="class-name" src="image1.png">
  <b>title1</b><br>content1
  <input 
    type="checkbox" 
    class="obtained" 
    onclick="obtained(this)" 
    name="obtained"
  >
</div><hr>
<div class="entry">
  <img class="class-name" src="image2.png">
  <b>title2</b><br>content2
  <input 
    type="checkbox" 
    class="obtained" 
    onclick="obtained(this)" 
    name="obtained"
  />
</div><hr>
<div class="entry">
  <img class="class-name" src="image3.png">
  <b>title3</b><br>content3
  <input 
    type="checkbox" 
    class="obtained" 
    onclick="obtained(this)" 
    name="obtained"
  />
</div><hr>

Related