Instead of $.closest in Angularjs
Asked Answered
O

3

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');
Omar answered 8/2, 2016 at 14:25 Comment(0)
C
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");
Catchpenny answered 8/2, 2016 at 14:37 Comment(0)
W
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");
Wakefield answered 15/12, 2016 at 14:28 Comment(0)
C
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");
Catchpenny answered 8/2, 2016 at 14:37 Comment(0)
G
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().

Gintz answered 8/2, 2016 at 14:29 Comment(1)
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.Sasin

© 2022 - 2024 — McMap. All rights reserved.