Skip to content

Instantly share code, notes, and snippets.

@hsnaydd
Last active March 18, 2016 08:00
Show Gist options
  • Select an option

  • Save hsnaydd/086af83ba6b30949e9a0 to your computer and use it in GitHub Desktop.

Select an option

Save hsnaydd/086af83ba6b30949e9a0 to your computer and use it in GitHub Desktop.

Revisions

  1. hsnaydd revised this gist Mar 18, 2016. 1 changed file with 79 additions and 1 deletion.
    80 changes: 79 additions & 1 deletion utility.js
    Original file line number Diff line number Diff line change
    @@ -8,4 +8,82 @@ function arrayRemove(array, value) {
    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;
    };
  2. hsnaydd created this gist Oct 14, 2015.
    11 changes: 11 additions & 0 deletions utility.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    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;
    }