Last active
November 28, 2024 00:49
-
-
Save rhysburnie/9d9db181c2d3ce298244 to your computer and use it in GitHub Desktop.
forEach function for looping results from `querySelectorAll`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Primarily for looping `querySelectorAll` results (`NodeList`) | |
| * | |
| * Avoid array hacks like: `[].forEach.call(NodeList)` | |
| * see: http://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/ | |
| */ | |
| +function(exports){ | |
| // exposed on this global object | |
| var exposed = 'notnative'; | |
| /** | |
| * so you can for each on `NodeList` | |
| * | |
| * @param [Array] can be a `querySelectorAll` result | |
| * @param [Function] | |
| * @param (optional) [Object] | |
| */ | |
| function forEach(array, callback, scope, fwd) { | |
| if(fwd) { | |
| for (var i = 0, c = array.length; i<c; i++) { | |
| callback.call(scope, i, array[i]); | |
| } | |
| } else { | |
| // ever so slightly faster | |
| for (var i = array.length; i--) { | |
| callback.call(scope, i, array[i]); | |
| } | |
| } | |
| }; | |
| exports[exposed] = exports[exposed] || {}; | |
| exports[exposed].foreach = forEach; | |
| }(this); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
EXAMPLE:
notnative.foreach(document.querySelectorAll('a'), function(i,v){console.log(v);});