From 2f94000c0a3729d5c3ebed4e9aa1847a1faa0739 Mon Sep 17 00:00:00 2001 From: Martin Angers Date: Sun, 4 Nov 2012 20:31:03 -0500 Subject: [PATCH] start closest with selector string --- traversal.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/traversal.go b/traversal.go index b4ec85a..5c2a101 100644 --- a/traversal.go +++ b/traversal.go @@ -93,6 +93,23 @@ func (this *Selection) ParentFiltered(selector string) *Selection { return filterAndPush(this, getParentNodes(this.Nodes), selector) } +// Closest() gets the first element that matches the selector by testing the +// element itself and traversing up through its ancestors in the DOM tree. +func (this *Selection) Closest(selector string) *Selection { + cs := cascadia.MustCompile(selector) + + return pushStack(this, mapNodes(this.Nodes, func(i int, n *html.Node) []*html.Node { + // For each node in the selection, test the node itself, then each parent + // until a match is found. + for ; n != nil; n = n.Parent { + if cs.Match(n) { + return []*html.Node{n} + } + } + return nil + })) +} + // Parents() gets the ancestors of each element in the current Selection. It // returns a new Selection object with the matched elements. func (this *Selection) Parents() *Selection {