Snippets for Vanilla JS Coding
When coding in VanillaJS, I usually create shortcuts:
const D = document const $ = D.querySelector.bind(D) const $$ = (selector, elem = D) => elem.querySelectorAll(selector)With that dollar functions, you can already use a syntax that is similar to jQuery:
$('#button').onclick = () => { alert('You clicked me!') } $$('.button').map(btn => { btn.style.backgroundColor = 'red' })When it comes to event handling, having an
onmethod can be useful:Array.prototype.on = function(type, listener, options) { this.map(el => { if (el instanceof Element) { el.addEventListener(type, listener, options) } }) return this // for chaining } $$('.button').on('click', e => { const btn = e.target alert('You clicked ' + btn.textContent) }).on('mouseover', e => { const btn = e.target btn.style.backgroundColor = 'red' }).on('mouseout', e => { const btn = e.target btn.style.backgroundColor = 'blue' })