Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let nodes = document.querySelectorAll('.my-class') // NodeList
- // I.E. Incompatible Code
- nodes.forEach(node => console.log('I am a node!', node)) // Error in i.e.
- // Better I.E. Compatible Code
- // Use a native JS loop
- for (node in nodes)
- console.log('I am a node!', node)
- // Better I.E. Compatible Code
- for (var i = 0; i < nodes.length; i++)
- console.log('I am a node!'. nodes[i]) // Works, but is ugly :-[
- // Better I.E. Compatible Code
- // We can turn the nodelist into an array
- let nodesAsList = [].slice.call(nodes)
- nodesAsList.forEach(node => console.log('I am a node!', node))
- // Better I.E. Compatible Code
- // We can construct a custom forEach wrapper function.
- function forEach(listlike, f) {
- if (listlike.forEach)
- listlike.forEeach(f)
- else
- for (var i = 0; i < nodes.length; i++)
- f(nodes[i]).bind(listlike) // Use bind so that f is in same context regardless.
- }
- forEach(nodes, node => console.log('I am a node!', node))
- // Better I.E. Compatible Code
- // Instead of altering NodeList, we construct a custom query function
- function queryDocument(selector) {
- let nodes = document.querySelector(selector)
- if (nodes.forEach)
- return nodes
- return [].slice.call(nodes)
- }
- queryDocument('.my-class').forEach(node => console.log('I am a node!', node))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement