3 ms·
The sizzle library that jQuery uses takes advantage of querySelectorAll. https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/externa
by mark242 9y ago
The sizzle library that jQuery uses takes advantage of querySelectorAll.
https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/external/sizzle/dist/sizzle.js#L293 https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1...
...only with a ton of wrapper code around it in order to support IE9 and below. If you don't have to support ancient browsers, there's no reason you can't write QSA code.
var nodes = document.querySelectorAll("li"); for(var i=0; i<nodes.length; i++) { nodes[i].classList.add("foo"); }
Yes it's slightly more code. It's also going to run a hell of a lot faster on, eg, a mobile device.
- 52-6F-62 9y agoLol. You beat me to it. Kudos.
- megous 9y agoI prefer: for (let node of document.querySelectorAll("li")) node.classList.add('foo'); or: Array.from(document.querySelectorAll("li")).forEach(node => node.classList.add('foo')) And if any particular pattern repeats in the code I'm writing I'll just create a helper function for that pattern (most of the time locally). Like: let qsa => s => Array.from(document.querySelectorAll(s)); There's nothing to test about that.
- loganfsmyth 9y agoYou don't even need the `Array.from` anymore. `.forEach` on `NodeList` is standard https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach https://developer.mozilla.org/en-US/docs/Web/API/NodeList/fo..., so all you need to do is load a polyfill for that.
- Flenser 9y agoYou might want to do map or filter before you do forEach. In which case you would need to convert it to an array.
- deleted 9y ago[deleted]