jQuery has a lovely if somewhat misnamed method called closest() that walks up the DOM tree looking for a matching element. For example, if I've got this HTML:
<table src="foo">
<tr>
<td>Yay</td>
</tr>
</table>
Assuming element
is set to <td>
, then I can figure the value of src
like this:
element.closest('table')['src']
And that will cleanly return "undefined" if either of the table element or its src attribute are missing.
Having gotten used to this in Javascriptland, I'd love to find something equivalent for Nokogiri in Rubyland, but the closest I've been able to come up with is this distinctly inelegant hack using ancestors():
ancestors = element.ancestors('table')
src = ancestors.any? ? first['src'] : nil
The ternary is needed because first returns nil if called on an empty array. Better ideas?
You can also do this with xpath:
You want the
src
attribute of the closest table ancestor, if it exists? Instead of getting an element that might exist via XPath and then maybe getting the attribute via Ruby, ask for the attribute directly in XPath:You'll get either the attribute or nil:
You can call
first
on an empty array, the problem is that it will returnnil
and you can't saynil['src']
without getting sad. You could do this:And if you're in Rails, you could use
try
thusly:If you're doing this sort of thing a lot then hide the ugliness in a method:
and then
You could also patch it right into Nokogiri::XML::Node (but I wouldn't recommend it):