JavaScript: reperire il genitore più prossimo di un dato elemento

JavaScript: reperire il genitore più prossimo di un dato elemento

In JavaScript è possibile reperire il genitore più prossimo di un dato elemento.

La soluzione è la seguente:


'use strict';

const closestParent = (el, selector, includeSelf = false) => {
    let 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;
};

Torna su