Skip to content

Instantly share code, notes, and snippets.

@hsnaydd
Last active March 18, 2016 08:00
Show Gist options
  • Save hsnaydd/086af83ba6b30949e9a0 to your computer and use it in GitHub Desktop.
Save hsnaydd/086af83ba6b30949e9a0 to your computer and use it in GitHub Desktop.
function includes(array, obj) {
return Array.prototype.indexOf.call(array, obj) != -1;
}
function arrayRemove(array, value) {
var index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
}
return index;
}
/**
* @param {Element} el
* @param {string} selector
* @return {Element[]}
*/
h.children = function(el, selector) {
var selectors = null,
children = null,
childSelectors = [],
tempId = '';
selectors = selector.split(',');
if (!el.id) {
tempId = '_temp_';
el.id = tempId;
}
while (selectors.length) {
childSelectors.push('#' + el.id + '>' + selectors.pop());
}
children = document.querySelectorAll(childSelectors.join(', '));
if (tempId) {
el.removeAttribute('id');
}
return children;
};
/**
* @param {Element} el
* @param {string} selector
* @param {boolean} [includeSelf]
* @return {Element|null}
*/
h.closestParent = function(el, selector, includeSelf) {
var parent = el.parentNode;
if (includeSelf && el.matches(selector)) {
return el;
}
while (parent && parent !== document.body) {
if (parent.matches && parent.matches(selector)) {
return parent;
} else if (parent.parentNode) {
parent = parent.parentNode;
} else {
return null;
}
}
return null;
};
/**
* @param {Element} el
* @param {string} [selector]
* @return {number}
*/
h.index = function(el, selector) {
var i = 0;
while ((el = el.previousElementSibling) !== null) {
if (!selector || el.matches(selector)) {
++i;
}
}
return i;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment