Search code examples
javascriptdomnative-codenodelist

javascript nodelist associate click


I'm willing to learn to manipulate the DOM with JS this holiday I'm starting with simple things, like:

var sliderControler = document.getElementsByClassName("slider-controler");
var slideAtual = 0;

for(i = 0; i < sliderControler.length;i++) {
  sliderControler[i].click(function(){
    console.log("I love to screw my brain with js");
  })
}

Why I cannot associate this event? I have a node list right?

document.getElementsByClassName then, returns a nodeList, and jQuery $(".slider-controler") returns a object.

what is the difference between the object returned from jQuery the nodelist


Solution

  • Currently, you're firing a click event for each of the HTMLElements in theNodeList(sliderControler).

    Each of the elements of the NodeList is an HTMLElement. To bind a click handler to the elements in the NodeList use addEventListener or assign the handler to the onclick property.

    for(i = 0; i < sliderControler.length;i++) {
      sliderControler[i].addEventListener('click', function(){
        console.log("I love js");
      });
    }
    

    If you're using jQuery, you don't need to use a loop to bind a click handler.

    $('.sliderControler').click(function() {
        console.log("I love js");
    });