closest function

Element? closest(
  1. Element lowerBound,
  2. String selector, {
  3. Element? upperBound,
})

Returns the closest element in the hierarchy of lowerBound up to an optional upperBound (both inclusive) that matches selector, or null if no matches are found.

Implementation

Element? closest(Element lowerBound, String selector, {Element? upperBound}) {
  for (Element? element = lowerBound; element != null; element = element.parent) {
    if (element.matches(selector)) return element;
    if (upperBound != null && upperBound == element) break;
  }

  return null;
}