Hack #8. Master XPath Expressions
Tap into a powerful new way to find exactly what you're looking for on a page.
Firefox contains a little-known but powerful feature called XPath. XPath is a query language for searching the Document Object Model (DOM) that Firefox constructs from the source of a web page.
As mentioned in "Add or Remove Content on a Page"
[Hack #6]
, virtually every hack in this book revolves around the DOM. Many hacks work on a collection of elements. Without XPath, you would need to get a list of elements (for example, with document.getElementsByTagName) and then test each one to see if it's something of interest. With XPath expressions, you can find exactly the elements you want, all in one shot, and then immediately start working with them.
Tip
A good beginners' tutorial on XPath is available at http://www.zvon.org/xxl/XPathTutorial/General/examples.html.
Basic Syntax
To execute an XPath query, use the
document.evaluate function. Here's the basic syntax:
var snapshotResults = document.evaluate('XPath expression',
document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);The function takes five parameters:
- The XPath expression itself
More on this in a minute.
- The root node on which to evaluate the expression
If you want to search the entire web page, pass in
document. But you can also search just a part of the page. For example, to search within a<div id="foo">, passdocument.getElementById("foo")as the second parameter.- A namespace resolver function
You can use ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access