From 971be3c4e428f5ef275d006c702ad436af85b599 Mon Sep 17 00:00:00 2001 From: Martin Angers Date: Thu, 8 Nov 2012 21:08:24 -0500 Subject: [PATCH] add nodes and selection overloads for Closest --- traversal.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/traversal.go b/traversal.go index 5c2a101..6a124ae 100644 --- a/traversal.go +++ b/traversal.go @@ -110,6 +110,31 @@ func (this *Selection) Closest(selector string) *Selection { })) } +// ClosestNodes() gets the first element that matches one of the nodes by testing the +// element itself and traversing up through its ancestors in the DOM tree. +func (this *Selection) ClosestNodes(nodes ...*html.Node) *Selection { + 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 isInSlice(nodes, n) { + return []*html.Node{n} + } + } + return nil + })) +} + +// ClosestSelection() gets the first element that matches one of the nodes in the +// Selection by testing the element itself and traversing up through its ancestors +// in the DOM tree. +func (this *Selection) ClosestSelection(s *Selection) *Selection { + if s == nil { + return pushStack(this, nil) + } + return this.ClosestNodes(s.Nodes...) +} + // 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 {