Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there an equivalent to jquery's "closest" in Dart

Tags:

dart

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');
like image 857
Alan Humphrey Avatar asked May 08 '13 16:05

Alan Humphrey


1 Answers

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>
like image 102
Shailen Tuli Avatar answered Nov 04 '22 15:11

Shailen Tuli