1

I wonder how to add event listener to all elements except for a few selected? I prefer to not use jQuery, because it's harder to debug on Chrome's developer tools. (You can see which handler is attached in each object Chrome's developer tools if you're not using jQuery)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
einstein
  • 13,389
  • 27
  • 80
  • 110
  • 3
    Are you sure you need a listener on all elements? Why not put a single listener on the document (body element) and don't run the logic if the event is from one of the elements you want to exclude. – RobG Apr 11 '11 at 22:57
  • I don't think jQuery makes JavaScript any harder to debug, and it makes writing widely compatible JavaScript ***so much easier.*** If you want to see an element's event listeners, look inside of the object returned by `$(element).data('event')`. – Matt Ball Apr 11 '11 at 23:01
  • RobG has the best solution. If for some reason you really do want the listener attached multiple times, you can use a slight variation, which is to loop through all of the elements in the document, and attach the event listener except for the items that meet the criteria for those you want to exclude. – Jason LeBrun Apr 11 '11 at 23:03
  • RobG how do you run the logic? I suppose you use it with javascript `this`, but that will always be the body element? – einstein Apr 11 '11 at 23:08
  • @Jason LeBrun: Yes but h0w do you loop through all elements? – einstein Apr 11 '11 at 23:13
  • Does this answer your question? [Add event listener to all objects except for a few selected?](https://stackoverflow.com/questions/5633064/add-event-listener-to-all-objects-except-for-a-few-selected) – Brian Tompsett - 汤莱恩 Jul 09 '22 at 09:02

1 Answers1

2

You could also attach an (probably empty) class to all elements you want to attach an event listener to. Then you can get all elements you need by this class name and attach the event listener.

You may have a look at this question: Using addEventListener and getElementsByClassName to pass an element id