Skip to content

Instantly share code, notes, and snippets.

@atelierbram
Created November 14, 2018 20:07
Show Gist options
  • Save atelierbram/bc9f3f9079d451758ad1168bd7d581b5 to your computer and use it in GitHub Desktop.
Save atelierbram/bc9f3f9079d451758ad1168bd7d581b5 to your computer and use it in GitHub Desktop.
A common need when writing vanilla JavaScript is to find a selection of elements in the DOM and loop over them. For example, finding instances of a button and attaching a click handler to them.
let buttons = document.querySelectorAll("button");
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
// http://kangax.github.io/compat-table/es6/#for..of_loops
for (const button of buttons) {
button.addEventListener('click', () => {
console.log("for of worked");
});
}
// Could force it...
// NodeList.prototype.forEach = Array.prototype.forEach;
// Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
buttons.forEach((button) => {
button.addEventListener('click', () => {
console.log("forEach worked");
});
});
[...buttons].forEach((button) => {
button.addEventListener('click', () => {
console.log("spread forEach worked");
});
});
// Hacky? http://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
[].forEach.call(buttons, (button) => {
button.addEventListener('click', () => {
console.log("array forEach worked");
});
});
// Most old school
for (let i = 0; i < buttons.length; ++i) {
buttons[i].addEventListener('click', () => {
console.log("for loop worked");
});
}
const forEach = (array, callback, scope) => {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
forEach(buttons, (index, button) => {
console.log(index, button); // passes index + value back!
});
const els = Array.prototype.slice.apply(
document.querySelectorAll("button")
);
els.forEach((button) => {
console.log("apply worked");
});
@atelierbram
Copy link
Author

Taken from CSS-tricks

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