Question

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

Était-ce utile?

La 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");
});

Autres conseils

You can handle the click event for an Element with addEventListener

sliderControler[i].addEventListener('click', function() {
    console.log("I love to mess my brain with js");
});

With jQuery you could just do the following to handle the click event for all elements with class .slider-controler

$('.slider-controler').on('click', function () {
    console.log("I love to mess my brain with js");
});

The value returned from jQuery is not a true NodeList, but instead is a special jQuery object. The jQuery click() method accepts a function as an event handler like you have in your code above, howver the native Element object does not.

try Changing sliderController.click(function... To sliderController.onclick = function...

The object returned by the jQuery selector is a jQuery-wrapped collection of elements. The methods you have directly available on DOM elements are quite different.

I would suggest, as a start, the MDN documentation on the Element interface: https://developer.mozilla.org/en-US/docs/Web/API/element

For binding events, you typically have two options:

  1. Use the corresponding on* attribute:

    sliderController[i].onclick = function() {
      /* ... */
    }
    

    That is typically discouraged though, as it makes you unable to bind more than one handler to a given event.

  2. Use addEventListener:

    sliderController[i].addEventListener("click", function() {
      /* ... */
    });
    

You might want to check out some notes on MDN about addEventListener vs on*

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top