Created
November 14, 2018 20:07
-
-
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.
This file contains 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
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"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken from CSS-tricks