Is jquery equivalent "closest" to Dart

jQuery has a "closest" that returns the closest matching ancestor in the tree. Is there a dart? I would like to make the following less fragile:

e.target.parent.parent.nextElementSibling.classes.toggle('hide'); 

maybe something like:

 e.target.closest('div').nextElementSibling.classes.toggle('hide'); 
+6
source share
1 answer

As far as I know, the built-in function does not exist. But it's pretty easy to code something.

The findClosestAncestor() function, defined below, finds the predefined element for the element specified by the ancestor tag:

 <!DOCTYPE html> <html> <head> <title>ancestor</title> </head> <body> <div id='outer'> <div id='inner'> <p></p> </div> </div> <script type="application/dart"> import 'dart:html'; Element findClosestAncestor(element, ancestorTagName) { Element parent = element.parent; while (parent.tagName.toLowerCase() != ancestorTagName.toLowerCase()) { parent = parent.parent; if (parent == null) { // Throw, or find some other way to handle the tagName not being found. throw '$ancestorTagName not found'; } } return parent; } void main() { ParagraphElement p = query('p'); Element parent = findClosestAncestor(p, 'div'); print(parent.id); // 'inner' } </script> <script src="packages/browser/dart.js"></script> </body> </html> 
+4
source

Source: https://habr.com/ru/post/944549/


All Articles