Тома Томов Тома Томов - 1 year ago 71
Javascript Question

is it the right way to attach the function to each element

Is it the right way to atach the function to each element ? And is my function ok?

<ul id='forShopping'>
<li><input class='ch' type='checkbox' onclick='isActive()'> Air-freshener</input></li>
<li><input class='ch' type='checkbox' onclick='isActive()'> Pampers</input></li>
<li><input class='ch' type='checkbox' onclick='isActive()'> Newspapper</input></li>
<li><input class='ch' type='checkbox' onclick='isActive()'> Toilet paper</input></li>

function isActive () {
let elem = document.getElementsByTagName('input');
for(let i=0; i<elem.length; i++){
if(elem[i].checked == true){
elem[i].parentNode.style.backgroundColor = 'forestGreen';
elem[i].parentNode.style.backgroundColor = 'white';

It works this way but i`m not sure it is properly.

Answer Source

Though your code will work , but still it will be a costly process, since on every click it have to get element from with specific tag from DOM, & will loop through it. Instead pass the context of this with the function.

hope this snippet will be useful


function isActive(elem) {
 if (elem.checked == true) {
    elem.parentNode.style.backgroundColor = 'forestGreen';
  } else {
    elem.parentNode.style.backgroundColor = 'white';



<ul id='forShopping'>
    <input class='ch' type='checkbox' onclick='isActive(this)'> Air-freshener></li>
    <input class='ch' type='checkbox' onclick='isActive(this)'> Pampers></li>
    <input class='ch' type='checkbox' onclick='isActive(this)'> Newspapper></li>
    <input class='ch' type='checkbox' onclick='isActive(this)'> Toilet paper></li>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download