Finding closest element without jQuery

Very simple:

el.closest('tbody')

Supported on all browsers except IE.
UPDATE: Edge now support it as well.

No need for jQuery.
More over, replacing jQuery’s $(this).closest('tbody') with $(this.closest('tbody')) will increase performance, significantly when the element is not found.

Polyfill for IE:

if (!Element.prototype.matches) Element.prototype.matches = Element.prototype.msMatchesSelector;
if (!Element.prototype.closest) Element.prototype.closest = function (selector) {
    var el = this;
    while (el) {
        if (el.matches(selector)) {
            return el;
        }
        el = el.parentElement;
    }
};

Note that there’s no return when the element was not found, effectively returning undefined when the closest element was not found.

For more details see:
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

Leave a Comment