How Can I Access My Parent Li Element Using Javascript?
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 tried pa
Solution 1:
You can pass this
keyword to the function so that you can identify the closest li element of the clicked checkbox:
functionmyfunction(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;}
<divclass="container"><ulid="mylist"><liclass="mycheck"><inputtype="checkbox"class="status"onclick="myfunction(this)" ><labelclass="mytodo">make tea</label></li><liclass="mycheck"><inputtype="checkbox"class="status"onclick="myfunction(this)"><labelclass="mytodo">notes making</label></li><liclass="mycheck"><inputtype="checkbox"class="status"onclick="myfunction(this)"><labelclass="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);
});
})
functionmyfunction(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;}
<divclass="container"><ulid="mylist"><liclass="mycheck"><inputtype="checkbox"class="status" ><labelclass="mytodo">make tea</label></li><liclass="mycheck"><inputtype="checkbox"class="status"><labelclass="mytodo">notes making</label></li><liclass="mycheck"><inputtype="checkbox"class="status"><labelclass="mytodo">set clothes</label></li></ul></div>
Post a Comment for "How Can I Access My Parent Li Element Using Javascript?"