5

I want to implement this code in directive but in jQLite this doesn't work How should this be done?

 var thisCell = element.closest('.sampleclass');
Jhourlad Estrella
  • 3,545
  • 4
  • 37
  • 66
Ehsan Ali
  • 1,362
  • 5
  • 25
  • 51

3 Answers3

4

There's an experimental version of .closest in Firefox and Chrome as shown on MDN - Element.closest()

With this in mind you could write something like this

var elm = document.querySelector('.myClass').closest();

or with angular.element

var elm = angular.element(document.querySelector('.myClass').closest());

Of course there's always exception to the rule (aka IE) and for them you could use the Polyfill which is also shown on MDN - Element.closest()

if (window.Element && !Element.prototype.closest) {
    Element.prototype.closest = 
    function(s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
            i,
            el = this;
        do {
            i = matches.length;
            while (--i >= 0 && matches.item(i) !== el) {};
        } while ((i < 0) && (el = el.parentElement)); 
        return el;
    };
}

I used this successfully to get the closest form of an element name by doing this line of code (it works in IE with the Polyfill:

var form document.querySelector('[name="elmName"]').closest("form");
ghiscoding
  • 12,308
  • 6
  • 69
  • 112
3

You have to implement this functionality manually, for example:

var thisCell = (function closest(e, className) {
  if (e[0].nodeName == "HTML") {
    return null;
  } else if (e.hasClass(className)) {
    return e;
  } else {
    return closest(e.parent(), className);
  }
})(element, "sampleclass");
sp00m
  • 47,968
  • 31
  • 142
  • 252
1

The documentation states that:

For lookups by tag name, try instead angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll().

  • This does not help if we need the closest parent that match something specific. i.e. you need the closest parent that has class `.item`. You want the one `.item` element that is the parent of the element you start with - not all `.item` elements in the page. – awe Dec 03 '19 at 10:24