Skip to main content

A jQuery.next() clone in Vanilla JS.

/**
 * A jQuery.next() clone in Vanilla JS.
 *
 * Modified version of:
 * https://gomakethings.com/converting-the-jquery-next-method-to-vanilla-js/
 *
 * @param {Element|String} parent The parent element or selector.
 * @param {String} [selector] Filter based on the specified selector, or return
 *     the next element if a selector wasn't specified.
 * @return {Element|null} If there's no selector to filter by, just return the
 *     element. Otherwise, check if the nextElem matches the selector using the
 *     matches() method. If it matches, return it; if not, return null.
 */
var next = function (parent, selector) {
    var elem;

    if (typeof parent === "string") {
        elem = document.querySelector(parent);

        if (!elem) {
            return null;
        }
    } else {
        elem = parent;
    }

    // Get the next element
    var nextElem = elem.nextElementSibling;

    // If there's no selector, return the next element
    if (!selector) {
        return nextElem;
    }

    // Otherwise, check if the element matches the selector
    if (nextElem && nextElem.matches(selector)) {
        return nextElem;
    }

    // if it's not a match, return null
    return null;
};