Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 948
Ehsan Ali Avatar asked Feb 08 '16 14:02

Ehsan Ali


People also ask

What is closest in angular?

closest() The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.

What is $element in AngularJS?

element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular. element can be either used as an alias for the jQuery function or it can be used as a function to wrap the element or string in Angular's jqlite. Syntax: angular.element(element)

What is closest method in Javascript?

The closest() method searches up the DOM tree for elements which matches a specified CSS selector. The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found. The closest() method returns null() if no match is found.

Can we use document getElementById in AngularJS?

You can use document. getElementById() in Angularjs, but manipulating HTML in a controller is not a good practice.


1 Answers

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");
like image 81
ghiscoding Avatar answered Sep 24 '22 06:09

ghiscoding