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
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>