0

My mission in this exercise is to toggle the "done" attribute of the li items on the list whenever someone clicks on them. I found other ways of doing so, but this one didn't work for me and I'm eager to understand why. What's wrong with my code? isn't it possible to assign handlers like that, or maybe something else in my code is wrong?

var liList = document.querySelectorAll("li");
for (var i = 0; i < liList.length; ++i){
    liList[i].onItemClick = function() {
    liList[i].classList.toggle("done");
    }
}
<ul>
   <li>Notebook</li>
   <li>Jello</li>
   <li>Spinach</li>
   <li>Rice</li>
   <li>Birthday Cake</li>
   <li>Candles</li>
</ul>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tm9hbQn
  • 170
  • 1
  • 3
  • 13

4 Answers4

2

use 'onClick' instead of 'onItemClick'

window.addEventListener('load', function() {
  document.querySelectorAll("li").forEach(function(v){
    v.addEventListener("click", function(e){
      e.target.classList.toggle("done");
    })
  })
})
li.done {
  color: green
}
<ul>
  <li>Notebook</li>
  <li>Jello</li>
  <li>Spinach</li>
  <li>Rice</li>
  <li>Birthday Cake</li>
  <li>Candles</li>
</ul>
Akash Shrivastava
  • 1,365
  • 8
  • 16
  • hi, so in your solution the v handed over to the function is the html object being selected? and what's the e? I'm new to js and can't really tell the rules about all that information being handed over to functions. – Tm9hbQn Jan 02 '20 at 10:11
  • @user2396866 yes, `v` is the html object, and `e` is the event object, when an `li` is clicked, an event is raised, `e` holds that event information, `e.target` holds the HTML object on which event was raised. – Akash Shrivastava Jan 02 '20 at 10:13
  • 1
    and like i've already realized, everytime something "holds" an item, changing the something changes the item itself, right? thank you very much for the help! – Tm9hbQn Jan 02 '20 at 10:16
1
var liList = document.querySelectorAll("li");

for (var i = 0; i < liList.length; ++i){
    liList[i].addEventListener("click", function() {
        this.classList.toggle("done");
    });
}
  • thank you, it worked just like I wanted. Just wanted to ask - what are the rules regarding the use of "this" in javascript? everytime I assign a function to an event handler, "this" will refer to the object being clicked/hovered/etc? – Tm9hbQn Jan 02 '20 at 10:13
  • Basically 'this' keyword refer the current element inside the loop on click event. – Muhammad Daniyal Jan 02 '20 at 10:28
0

Try liList[i].onclick = function(e) {console.log(e.currentTaget)}

the e will be your current clicked item.

Pomelo
  • 1
0
**This may be helpful for you**

  <script type="text/javascript">
    var liList = document.getElementsByTagName("li");
    for(var i=0; i<liList.length; i++){
     liList[i].addEventliListener("click", liClick);
    }
    function liClick(){
      this.classliList.toggle("done");
    }
    </script>
Manoj
  • 113
  • 1
  • 1
  • 7