How on pure js compare the digital value of the element

and if it is greater than 0, then give this element (or another element) an extra class?

1 answer 1

The usual comparison operator is used for this: if(условие){если да, то выполнить это}else{если нет, то выполнить это};

 function check() { var num = document.querySelectorAll('input[type="checkbox"]:checked').length; if(num > 0){ document.getElementById('checkbox').classList.add("s1"); document.getElementById('checkbox').classList.remove("s0"); }else{ document.getElementById('checkbox').classList.add("s0"); document.getElementById('checkbox').classList.remove("s1"); }; }; 
 #checkbox {width:20px;height: 20px;} #checkbox.s0 {background-color: black} #checkbox.s1 {background-color: green} 
 <body onload="check()"> <input type="checkbox" onclick="check()"> <input type="checkbox" onclick="check()"> <input type="checkbox" onclick="check()"> <div id="checkbox"> </div> 

  • And if the value changes without reloading the page? - Frontendman
  • @Frontendman, when you click on the button for example? - Yuri
  • I have a lot of checkboxes and a script that counts the number of checked checkboxes. And I need to push another element (assign / delete a class) if at least one is selected. - Frontendman
  • @Frontendman events to help you - Sublihim
  • @Frontendman, look, I changed the answer. But if you need to remove or add a certain class, here’s the article: ruseller.com/lessons.php?rub=32&id=2131 - Yuri