nemesarial / DOMHelper

    var DOM = {
        create(tag, classes, attributes, content) {
            let elem = document.createElement(tag);
            elem.className = classes;
            for (let attribute in attributes) {
                elem.setAttribute(attribute, attributes[attribute]);
            }
            if (content) {
                if (content instanceof HTMLElement) {
                    elem.appendChild(content);
                } else {
                    elem.innerHTML = content;
                }
            }
            return elem;
        },
        queryAll(selector, elem) {
            elem = elem instanceof HTMLElement ? elem : document;

            const toArray = function(coll, fromIndex) {
                return Array.prototype.slice.call(coll, fromIndex);
            };

            return toArray(elem.querySelectorAll(selector));
        },
        query(selector, elem) {
            let ret = DOM.queryAll(selector, elem);
            return ret.length > 0 ? ret[0] : null;
        },

        //TODO: Refactor this -- it is way too slow; Element.matches(selector)
        getClosest(elem, selector, inclusive = false) {
            let firstChar = selector.charAt(0);

            // Get closest match
            for (; elem && elem !== document; elem = elem.parentNode) {
                // If selector is a class
                if (firstChar === '.') {
                    if (elem.classList.contains(selector.substr(1))) {
                        return elem;
                    }
                }

                // If selector is an ID
                if (firstChar === '#') {
                    if (elem.id === selector.substr(1)) {
                        return elem;
                    }
                }

                // If selector is a data attribute
                if (firstChar === '[') {
                    if (elem.hasAttribute(selector.substr(1, selector.length - 2))) {
                        return elem;
                    }
                }

                // If selector is a tag
                if (elem.tagName.toLowerCase() === selector) {
                    return elem;
                }
            }

            return false;
        }
    };