jQuery has "closest" which returns the closest matching ancestor in the tree. Is there a Dart equivalent? I'd like to make the following less fragile:
e.target.parent.parent.nextElementSibling.classes.toggle('hide');
perhaps something like:
e.target.closest('div').nextElementSibling.classes.toggle('hide');
There isn't a builtin function as far as I know. But it's pretty easy to code up something.
The findClosestAncestor()
function defined below finds the closet ancestor for an element given 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>
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