0

I know how to do so with jQuery, and I know how to do so with event delegation. But how do you do so in plain JavaScript?

For example, how do you assign an event handler to a bunch of lis?

I see that var li = document.querySelectorAll('li');. Returns an array-like thing. Do you just loop through and assign handlers? I feel like there must be a better way. If not, what's the best way to loop through the array-like thing (and what is the array-like thing called?)?

4
  • 1
    Is this a serious question? Yes, when you have a collection, and you want to apply some behavior to each element in the collection, you can iterate the collection and operate on individual members. There is no better way. This is exactly what jQuery does. Commented Oct 14, 2014 at 1:46
  • @squint I figured that there would be a way to do something like li.<add listeners to each>. I'm still learning to program, but in hindsight what you said makes sense. Still, I think it's a completely understandable question for a student to have. Commented Oct 14, 2014 at 1:50
  • 1
    you should probably use delegation instead of adding a lot of events manually in a loop. you just buind the click (or whatever) to the UL instead of the LI, and check e.target instead of this inside the handler. Commented Oct 14, 2014 at 2:09
  • Four word answer: "One at a time". Commented Oct 14, 2014 at 3:15

1 Answer 1

1

Yes, you should loop through the collection and assign the handlers individually. jQuery also does this behind the scenes.

querySelectorAll returns a NodeList which is an array-like object.

For looping through the list, you can either use a for loop:

var list = document.querySelectorAll('li'),
    l = list.length,
    li;

for (var i = 0; i < l; i++) {
   li = list.item(i);
   // ...
} 

Or use the forEach method:

[].forEach.call(document.querySelectorAll('li'), function(li) {
    // ...
});
Sign up to request clarification or add additional context in comments.

3 Comments

How do you loop through it? forEach isn't working.
@AdamZerner: With a for loop. "array-like" means that the object has a length and numerical properties.
Ok, thanks. I wasn't sure what the keys were so I was afraid to do a for loop but the keys seem to be numerical indicies like an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.