DEV Community

Discussion on: Snippets for Vanilla JS Coding

Collapse
 
learosema profile image
Lea Rosema (she/her) • Edited

Another option is to attach the on method plus Array.prototype.map to the NodeList prototype instead:

const $$ = (selector, startNode = D) => startNode.querySelectorAll(selector)
NodeList.prototype.map = Array.prototype.map
NodeList.prototype.on = function(type, listener, options) {
  this.map(el => {
    if (el instanceof Element) {
      el.addEventListener(type, listener, options)
    }
  })
  return this // for chaining
}

This keeps the Array prototype clean =).