2

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);
}
7
  • 1
    Do you mean .closest()? Dec 13, 2016 at 19:25
  • This might do what you want github.com/bwu-dart/bwu_utils/blob/master/lib/browser/… Dec 13, 2016 at 19:51
  • @jinglesthula thanks for that. I mixed up i think. Closest is what i wanted, yeah. Dec 13, 2016 at 20:19
  • @GünterZöchbauer I think that is what i would want. Maybe ill implement some of code in our application. :) Dec 13, 2016 at 20:20
  • @GünterZöchbauer I noticed the Element class within Dart:html, has a closest(selector) function and was looking through that. I noticed that it also is the parent class for HtmlElement, so i was thinking that concept of closest might be just as good as yours? I didnt see any documentation for it to describe it other than its signature really: Element closest(String selector); Dec 14, 2016 at 15:29

1 Answer 1

1

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.