SHARE
TWEET

Untitled

a guest Jul 21st, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let nodes = document.querySelectorAll('.my-class') // NodeList
  2.  
  3. // I.E. Incompatible Code
  4.  
  5. nodes.forEach(node => console.log('I am a node!', node))  // Error in i.e.
  6.  
  7. // Better I.E. Compatible Code
  8. // Use a native JS loop
  9.  
  10. for (node in nodes)
  11.   console.log('I am a node!', node)
  12.  
  13. // Better I.E. Compatible Code
  14.  
  15. for (var i = 0; i < nodes.length; i++)
  16.   console.log('I am a node!'. nodes[i]) // Works, but is ugly :-[
  17.  
  18. // Better I.E. Compatible Code
  19. // We can turn the nodelist into an array
  20.  
  21. let nodesAsList = [].slice.call(nodes)
  22.  
  23. nodesAsList.forEach(node => console.log('I am a node!', node))
  24.  
  25. // Better I.E. Compatible Code
  26. // We can construct a custom forEach wrapper function.
  27.  
  28. function forEach(listlike, f) {
  29.   if (listlike.forEach)
  30.     listlike.forEeach(f)
  31.   else
  32.     for (var i = 0; i < nodes.length; i++)
  33.       f(nodes[i]).bind(listlike) // Use bind so that f is in same context regardless.
  34. }
  35.  
  36. forEach(nodes, node => console.log('I am a node!', node))
  37.  
  38. // Better I.E. Compatible Code
  39.  
  40. // Instead of altering NodeList, we construct a custom query function
  41. function queryDocument(selector) {
  42.   let nodes = document.querySelector(selector)
  43.  
  44.   if (nodes.forEach)
  45.     return nodes
  46.  
  47.   return [].slice.call(nodes)
  48. }
  49.  
  50. queryDocument('.my-class').forEach(node => console.log('I am a node!', node))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top