How can i access my parent li element using javascript?

前端 未结 1 777
无人及你
无人及你 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;}
    <div class="container">
      <ul id="mylist">
    
        <li class="mycheck">
          <input type="checkbox" class="status" onclick="myfunction(this)" >
          <label class="mytodo">make tea</label>
        </li>
    
        <li class="mycheck">
          <input type="checkbox" class="status" onclick="myfunction(this)">
          <label class="mytodo">notes making</label>
        </li>
    
        <li class="mycheck">
          <input type="checkbox" class="status" onclick="myfunction(this)">
          <label class="mytodo">set clothes</label>
        </li>
    
      </ul>
    
    </div>

    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;}
    <div class="container">
      <ul id="mylist">
    
        <li class="mycheck">
          <input type="checkbox" class="status" >
          <label class="mytodo">make tea</label>
        </li>
    
        <li class="mycheck">
          <input type="checkbox" class="status">
          <label class="mytodo">notes making</label>
        </li>
    
        <li class="mycheck">
          <input type="checkbox" class="status">
          <label class="mytodo">set clothes</label>
        </li>
    
      </ul>
    
    </div>

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