Skip to content

Instantly share code, notes, and snippets.

@zoonderkins
Created July 28, 2018 09:42
Show Gist options
  • Save zoonderkins/e5776d2250cd8797b38790a705339f1e to your computer and use it in GitHub Desktop.
Save zoonderkins/e5776d2250cd8797b38790a705339f1e to your computer and use it in GitHub Desktop.
Vanilla javascript selector #javascript
const $$ = (selector, elem = D) =>
elem.querySelectorAll(selector)
// More different selector
const D = document
const $ = D.querySelector.bind(D)
const $$ = (selector, startNode = D) => [...startNode.querySelectorAll(selector)]
// html
<button id="button">click me!</button>
// selector
$('#button').onclick = () => {
alert('You clicked me!')
}
// multi html
<button> button 1 </button>
<button> button 2 </button>
<button> button 3 </button>
// multi selector
$$('button').map(btn => {
btn.style.backgroundColor = 'red'
})
// multi selector with event
$$('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'
})
//Reference: https://dev.to/terabaud/snippets-for-vanilla-js-coding-19cg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment