XPath: Difference between revisions
m →XPathResult Types: Link into resultTypes |
m Links into XPathExpression |
||
Line 1: | Line 1: | ||
{{stub}} | {{stub}} | ||
'''XPath''' (XML Path Language) is a language for addressing elements in a XML or HTML document. | '''XPath''' (XML Path Language) is a language for addressing elements in a XML or HTML document. [[XPathExpression|XPathExpressions]] describe paths in a tree represention of the document. | ||
XPath is very fast compared to manual DOM traversal (see e.g. [http://ejohn.org/blog/getelementsbyclassname-speed-comparison/ getElementsByClassName Speed Comparison]). | XPath is very fast compared to manual DOM traversal (see e.g. [http://ejohn.org/blog/getelementsbyclassname-speed-comparison/ getElementsByClassName Speed Comparison]). | ||
Line 17: | Line 17: | ||
== Relative paths == | == Relative paths == | ||
Note that relative | Note that relative [[XPathExpression|XPathExpressions]], that start from some specific node, do not begin with a <code>/</code>. Start them with a period, e.g. <code>.//a</code>, or an axis, e.g. <code>descendant::a</code>. The default axis is <code>child</code>, so just <code>a</code> works to find an immediate descendant. | ||
== Extensions == | == Extensions == |
Revision as of 01:54, 7 January 2009
XPath (XML Path Language) is a language for addressing elements in a XML or HTML document. XPathExpressions describe paths in a tree represention of the document.
XPath is very fast compared to manual DOM traversal (see e.g. getElementsByClassName Speed Comparison).
This page is intended for tips and gotchas related to using XPath in Greasemonkey scripts, not complete documentation. See the links below for that.
Using XPath in Greasemonkey
The most convenient way to use XPath in Greasemonkey scripts is with a helper function. The insides of that function illustrate the less convenient way. The native method is through the document.evaluate
function.
XPathResult resultTypes
Relative paths
Note that relative XPathExpressions, that start from some specific node, do not begin with a /
. Start them with a period, e.g. .//a
, or an axis, e.g. descendant::a
. The default axis is child
, so just a
works to find an immediate descendant.
Extensions
You can quickly determine the XPath to an element with the XPath Checker addon. Just right-click an element and select "XPath". A window will pop up with the expression. You can also experiment with new expressions interactively.
Another extension is XPather, which relies on DOM Inspector.
In FireBug, you can right-click a node in the HTML inspector and select "Copy XPath". A $x
function (like the XPath helper function linked above but with no support for specifying a context node) is available in the Firebug console.