JAVASCRIPT

JavaScript Document Object (DOM) Helpers

The Document object represents the root node of the HTML document. The nodes are organized in a tree structure, called the DOM tree. Objects in the DOM tree may be addressed and manipulated by using methods on the objects.

closest

export function getClosest(elem, selector) {
    // This allows for matching based on any selector, not just a single class.
    for (; elem && elem !== document; elem = elem.parentNode) {
        // Traverse up the dom until document is reached
        if (matches(elem, selector)) {
            // Test each element to see if it matches. If it does, return it.
            return elem
        }
    }
    return null;
}

export const closest = getClosest;

Usage for the above that’s in a file set up for tree shaking, e.g., helpers.js

import { closest } from 'js/helpers';

offset top

export function getOffsetTop(el) {
    let offsetTop = 0;
    do {
        if (!isNaN(el.offsetTop)) {
            offsetTop += el.offsetTop;
        }
    } while (el = el.offsetParent);
    return offsetTop;
}

next

export function next(el, selector) {
    if (el.nextElementSibling) {
        if (matches(el.nextElementSibling, selector)) {
            return el.nextElementSibling;
        } else {
            return prev(el.nextElementSibling, selector);
        }
    }

    return false;
}

previous

export function prev(el, selector) {
    if (el.previousElementSibling) {
        if (matches(el.previousElementSibling, selector)) {
            return el.previousElementSibling;
        } else {
            return prev(el.previousElementSibling, selector);
        }
    }

    return false;
}

siblings

export function siblings(el, selector) {
    return Array.prototype.filter.call(el.parentNode.children, function (child) {
        return matches(child, selector);
    }) || [];
}

Resources

comments powered by Disqus