How can i access my parent li element using javascript?

前端 未结 1 804
无人及你
无人及你 2021-01-29 09:29

I am a beginner in JavaScript and I can\'t figure out that how can I get the index of li whose checkbox is checked and add/remove the CSS class cut to that particular li. I trie

1条回答
  •  忘掉有多难
    2021-01-29 09:58

    You can pass this keyword to the function so that you can identify the closest li element of the clicked checkbox:

    function myfunction(el){
      if(el.checked){
        el.closest('li').classList.add('cut');
      }
      else{
        el.closest('li').classList.remove('cut');
      }
    }
    .cut{
      text-decoration: line-through;
      opacity: 0.4;
    }
    
    #mylist{list-style: none;}

    Attaching event using JavaScript:

    var checkboxes = document.querySelectorAll('.mycheck .status');
    checkboxes.forEach(function(chk){
      chk.addEventListener('click', function(){
        myfunction(this);
      });
    })
    function myfunction(el){
      if(el.checked){
        el.closest('li').classList.add('cut');
      }
      else{
        el.closest('li').classList.remove('cut');
      }
    }
    .cut{
      text-decoration: line-through;
      opacity: 0.4;
    }
    
    #mylist{list-style: none;}

    0 讨论(0)
提交回复
热议问题