tags:

views:

26

answers:

2

Given a node in an HTML document, N1, I need a concise way of finding the closest node to N1, say N2, with some tagName (e.g. to get the nearest link). I will be injecting the js code to do this into a remote browser (using Selenium) and so need it to be as concise as possible. I would otherwise write a recursive function that takes N1 and visits all siblings, then moves up and down the DOM tree until it finds a match.

Is there is a shortcut that doesn't rely on 3rd party libraries?

A: 

I don't think there's a more concise way than recursively searching the tree, no. It seems pretty concise to me. I don't think there are any shortcuts, either.

T.J. Crowder
hmmm. I was wondering if there was a way of creating a flattened tree structure that I could index into...
Joel
@Joel: You could certainly do that, writing out each element to an array with (say) its XPath-notated location. But to do that, you'd have to....recurse through the three to build the flat list. :-)
T.J. Crowder
@Crowder: groan
Joel
A: 

Try this:

http://v3.thewatchmakerproject.com/journal/329/finding-html-elements-using-javascript-nextsibling-and-previoussibling

quantumSoup
I think it's fairly clear Joel knows how to use `nextSibling` and `previousSibling`.
T.J. Crowder