Equivalent to nearest in Dart, specifically DartPolymer?

Issue

I am trying to figure out a way to carry out something similar to jquery’s nearest function. Ex:

$("a.test").nearest(".group-parent");

but in dart.

I was looking through the HtmlElement class to see if there was a way i could do as above but have not found anything really which would walk up the tree until it found the selector (or null, etc).

Is there something in place that can already be leveraged to do such a thing?

I was thinking to just create a function which will loop through the parents until parents = null (or whatever returns for the document).

HtmlElement findNearestClass(HtmlElement node, String classString){
  if (node == null) return null;
  if (node.classes.contains(classString)) return node;
  return findNearestClass(node.parent, classString);
}

Solution

After discussing with Gunter, We determined the following:

When you are creating a component with Dart, you will extend PolymerElement which based on the HtmlElement it seems. HtmlElement has a parent Element.

I was looking as such, and noticed in the Element class, there is actually a closest function which has the following signature

Element closest(String selectors);

which seems to resolve what I want, and can use References to HtmlElements or PolymerElmeent to do similar.

A common scenario which might be useful for your component might be something like:

(MouseEvent mouse){
  HtmlElement target = mouse.target;
  HtmlElement closestFoo = target.closest(".foo");
}

As an alternative, Gunter did link this, which has a closest implementation you could leverage. https://github.com/bwu-dart/bwu_utils/blob/master/lib/browser/html.dart#L49

Answered By – Fallenreaper

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *