Ehsan Ali
Ehsan Ali

Reputation: 1432

Instead of $.closest in Angularjs

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');

Upvotes: 5

Views: 5761

Answers (3)

ghiscoding
ghiscoding

Reputation: 13214

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");

Upvotes: 4

sp00m
sp00m

Reputation: 48837

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");

Upvotes: 3

user1817574
user1817574

Reputation:

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().

Upvotes: 1

Related Questions