Last active
April 30, 2017 14:14
-
-
Save blakewatson/2ce310fc6e8992b5903f7cdb520c5b75 to your computer and use it in GitHub Desktop.
A tiny wrapper around native DOM API functions. Designed to help me select elements more easily.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dom = (selector, el = null) => { | |
if(el) { | |
return Array.from(el.querySelectorAll(selector)); | |
} else { | |
return Array.from(document.querySelectorAll(selector)); | |
} | |
}; | |
dom.first = (selector, el = null) => { | |
if(el) { | |
return Array.from(el.querySelectorAll(selector))[0]; | |
} else { | |
return Array.from(document.querySelectorAll(selector))[0]; | |
} | |
}; | |
dom.on = (el, eventName, callback, preventDefault = false) => { | |
function listener(event) { | |
if(preventDefault) { | |
event.preventDefault(); | |
} | |
callback(event); | |
} | |
el.addEventListener(eventName, listener); | |
return listener; | |
}; | |
dom.off = (el, eventName, listener) => { | |
el.removeEventListener(eventName, listener); | |
}; | |
dom.show = el => { | |
el.style.display = ''; | |
}; | |
dom.hide = el => { | |
el.style.display = 'none'; | |
}; | |
dom.index = el => { | |
const parent = el.parentNode; | |
const children = Array.from(parent.childNodes).filter(child => child.nodeName !== '#text'); | |
return children.indexOf(el); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If people have suggestions for me, they are welcome. Keep in mind I'm not trying to make a robust, highly compatible library. Just wanting to make using the native APIs a little more terse.