Helper Methods

Writing your own helper methods

True, always having to iterate over elements to do something with them may be rather cumbersome compared to jQuery’s concise and chainable $('.foo').css({color: 'red'}) syntax. So why not simply write our own shorthand methods for things like this?

const $ = function $ (selector, context = document) { const elements = Array.from(context.querySelectorAll(selector)) return { elements, html (newHtml) { this.elements.forEach(element => { element.innerHTML = newHtml }) return this }, css (newCss) { this.elements.forEach(element => { Object.assign(element.style, newCss) }) return this }, on (event, handler, options) { this.elements.forEach(element => { element.addEventListener(event, handler, options) }) return this } // etc. } }