JS-find closest

by Shridhar Baddur

HTML

<ul class="todo-list">
  <li>
    <span>
                     <button class="btn-delete" onClick="var closestElem = getClosest(this, 'li');alert(closestElem)">
                        <i class="far fa-trash-alt"></i>
                     </button>
                  </span>List Item 1</li>
  <li>
    <span>
                     <button class="btn-delete">
                        <i class="far fa-trash-alt"></i>
                     </button>
                  </span>List Item 2</li>
  <li>
    <span>
                     <button class="btn-delete">
                        <i class="far fa-trash-alt"></i>
                     </button>
                  </span>List Item 3</li>
  <li>
    <span>
                     <button class="btn-delete">
                        <i class="far fa-trash-alt"></i>
                     </button>
                  </span>List Item 4</li>
  <li>
    <span>
                     <button class="btn-delete">
                        <i class="far fa-trash-alt"></i>
                     </button>
                  </span>List Item 5</li>
</ul>

JavaScript

/**
 * Get the closest matching element up the DOM tree.
 * @private
 * @param  {Element} elem     Starting element
 * @param  {String}  selector Selector to match against
 * @return {Boolean|Element}  Returns null if not match found
 */
var getClosest = function(elem, selector) {

  // Element.matches() polyfill
  if (!Element.prototype.matches) {
    Element.prototype.matches =
      Element.prototype.matchesSelector ||
      Element.prototype.mozMatchesSelector ||
      Element.prototype.msMatchesSelector ||
      Element.prototype.oMatchesSelector ||
      Element.prototype.webkitMatchesSelector ||
      function(s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
          i = matches.length;
        while (--i >= 0 && matches.item(i) !== this) {}
        return i > -1;
      };
  }

  // Get closest match
  for (; elem && elem !== document; elem = elem.parentNode) {
    if (elem.matches(selector)) 
    return elem;
  }

  return null;

};