4 ms·
Well one nice affordance jQuery offers, is you can do manipulations en-mass without having to write out a loop, or use Array.forEach(). This helps simplify eve
by mark_story 14y ago
Well one nice affordance jQuery offers, is you can do manipulations en-mass without having to write out a loop, or use Array.forEach(). This helps simplify event binding and manipulation code. Also there are selectors in jQuery that are not available in querySelectorAll. And lastly querySelectorAll has some pretty buggy implementations. jQuery smoothes these out.
- gildas 14y agoBinding event handlers in a loop is an anti-pattern greatly promoted by jQuery during several years. You should use event delegation.
- mark_story 14y agoSure but $('.clicky').on('click', doSomething); means no loops at all, and will bind events to all matching elements. I don't think there is a native API way to do this. Edit: typos
- MatthewPhillips 14y agodocument.getElementsByClassName('clicky').forEach(function(el) { el.addEventListener('click', doSomething); });
- d4n3 14y agoI'm not sure that works. getElementsByClassName (and Id and querySelector) returns a NodeList, not an Array, so there's no foreach, you have to convert it to an array first.
- MatthewPhillips 14y agoArray.prototype.slice.call(document.getElementsBy....
- mark_story 14y agoThat's also a ton of tying and a lot of code that a minifier can't reduce. I guess its possible, but do you really want to writing such verbose code?
- gildas 14y agoAs far as I know jQuery is written with "native API", so there is obviously a way to do this in JavaScript. document.body.addEventListener("click", function(e) { if (e.target.className == "clicky") { doSomething(); } }, false);