Skip to content

Instantly share code, notes, and snippets.

@rhysburnie
Last active November 28, 2024 00:49
Show Gist options
  • Select an option

  • Save rhysburnie/9d9db181c2d3ce298244 to your computer and use it in GitHub Desktop.

Select an option

Save rhysburnie/9d9db181c2d3ce298244 to your computer and use it in GitHub Desktop.
forEach function for looping results from `querySelectorAll`
/**
* 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);
@rhysburnie
Copy link
Author

EXAMPLE:

notnative.foreach(document.querySelectorAll('a'), function(i,v){console.log(v);});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment