0

I'm want to change background color using checkbox, but it work only once. Mean if i click it again nothing change.

<body>
    <label class="switch">
        <input type="checkbox" onclick="check();">
        <span class="slider round"></span>
    </label>
</body>

<script>
    function check() {
        if (document.getElementsByTagName('input').checked) {
            document.body.style.backgroundColor = 'white';
        } else {
            document.body.style.backgroundColor = 'black';
        }
    }
</script>
TalkingJson
  • 91
  • 2
  • 8
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Andreas Jun 23 '18 at 14:16
  • `getElementsByTagName('input')` returns a list, do `getElementsByTagName('input')[0]` – nick zoum Jun 23 '18 at 14:17
  • Try use search this answer for your question https://stackoverflow.com/questions/8206565/check-uncheck-checkbox-with-javascript – Slaawwa Jun 23 '18 at 14:21

2 Answers2

0

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name.

In this case you do not need to use getElementsByTagName() at all. Just pass this to the function so that you can refer that element in the function body like the following:

function check(chk) {
  if (chk.checked) {
      document.body.style.backgroundColor = 'white';
  } else {
      document.body.style.backgroundColor = 'black';
  }
}
<body>
    <label class="switch">
        <input type="checkbox" onclick="check(this);">
        <span class="slider round"></span>
    </label>
</body>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Because of getElementsByTagName will response a list of elements. In your case, you have to choose the first element to check the checked

function check() {
  if (document.getElementsByTagName('input')[0].checked) {
    document.body.style.backgroundColor = 'white';
  } else {
    document.body.style.backgroundColor = 'black';
  }
}
check();
<body>
    <label class="switch">
        <input type="checkbox" onclick="check();">
        <span class="slider round"></span>
    </label>
</body>
Shiny
  • 62
  • 2