Skip to content

Instantly share code, notes, and snippets.

@blakewatson
Last active April 30, 2017 14:14
Show Gist options
  • Save blakewatson/2ce310fc6e8992b5903f7cdb520c5b75 to your computer and use it in GitHub Desktop.
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.
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);
};
@blakewatson
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment