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');
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.
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)
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.
You can use document. getElementById() in Angularjs, but manipulating HTML in a controller is not a good practice.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With