Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding closest element without jQuery

Tags:

javascript

I am trying to find the closest element with a specific tag name without jquery. When I click on a <th> I want to get access to the <tbody> for that table. Suggestions? I read about offset but didn't really understand it too much. Should I just use:

Assume th is already set to clicked th element

th.offsetParent.getElementsByTagName('tbody')[0]
like image 994
hunterc Avatar asked Sep 06 '13 18:09

hunterc


3 Answers

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

like image 100
oriadam Avatar answered Oct 18 '22 22:10

oriadam


Little (very) late to the party, but nonetheless. This should do the trick:

function closest(el, selector) {
    var matchesFn;

    // find vendor prefix
    ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
        if (typeof document.body[fn] == 'function') {
            matchesFn = fn;
            return true;
        }
        return false;
    })

    var parent;

    // traverse parents
    while (el) {
        parent = el.parentElement;
        if (parent && parent[matchesFn](selector)) {
            return parent;
        }
        el = parent;
    }

    return null;
}
like image 71
Ales Avatar answered Oct 18 '22 21:10

Ales


Here's how you get the closest element by tag name without jQuery:

function getClosest(el, tag) {
  // this is necessary since nodeName is always in upper case
  tag = tag.toUpperCase();
  do {
    if (el.nodeName === tag) {
      // tag name is found! let's return it. :)
      return el;
    }
  } while (el = el.parentNode);

  // not found :(
  return null;
}

getClosest(th, 'tbody');
like image 22
Joon Avatar answered Oct 18 '22 22:10

Joon