Тома Томов Тома Томов - 17 days ago 8
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>
</ul>

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';
}else{
elem[i].parentNode.style.backgroundColor = 'white';
}
}
}


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

Answer

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

JS

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

}

HTML

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

JSFIDDLE