Skip to content

Instantly share code, notes, and snippets.

@Tahseenm
Last active November 23, 2016 20:38
Show Gist options
  • Save Tahseenm/bad8f5de8a6b623e33e42faa3be7cfa3 to your computer and use it in GitHub Desktop.
Save Tahseenm/bad8f5de8a6b623e33e42faa3be7cfa3 to your computer and use it in GitHub Desktop.
DOM Helpers
/**
* Wrapper for `addEventListener`
*
* @param {HTMLElement} target
* @param {string} eventType
* @param {function} eventHandler
* @param {boolean|Object.<boolean>} opt - useCapture OR
* {capture, once, passive} (NOTE: Low browser support)
*/
function on(target, eventType, eventHandler, opt = false) {
target.addEventListener(eventType, eventHandler, opt);
}
/**
* Wrapper for `removeEventListener`
*
* @param {HTMLElement} target
* @param {string} eventType
* @param {function} eventHandler - Listener to remove
* @param {boolean|Object.<boolean>} opt - useCapture OR
* {capture, passive} (NOTE: Low browser support)
*/
function off(target, eventType, eventHandler, opt = false) {
target.removeEventListener(eventType, eventHandler, opt);
}
/**
* Query for first element that matches the CSS selector
*
* @param {string} selector - CSS selector
* @param {HTMLElement} scope
* @returns {?HMTLElement}
*/
function query(selector, scope = document) {
return scope.querySelector(selector);
}
/**
* Query all elements that matches the CSS selector
*
* @param {string} selector - CSS selector
* @param {HTMLElement} scope
* @returns {NodeList}
*/
function queryAll(selector, scope = document) {
const results = scope.querySelectorAll(selector);
if (!result.forEach) results.forEach = Array.prototype.forEach;
return results;
}
/**
* Closest parent with given Tag
*
* @param {HTMLElement} element
* @param {string} _tagName
* @returns {?HTMLElement}
*/
function findParentWithTag(element, _tagName) {
const parent = element.parentNode;
const tagName = _tagName.toUpperCase();
if (parent.tagName === tagName || !parent) return parent;
return findParentWithTag(parent, tagName);
}
/**
* Closest parent with given class
*
* @param {HTMLElement} element
* @param {string} className
* @returns {?HTMLElement}
*/
function findParentWithClass(element, className) {
const parent = element.parentNode;
if (parent.classList.contains(className) || !parent) return parent;
return findParentWithClass(parent, className);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment