[Greasemonkey] generating XPath string from dom node
Jonathan Buchanan
jonathan.buchanan at gmail.com
Thu Mar 16 16:16:33 EST 2006
Further to Matt's suggestion, if you want to select a specific
element, you'll need the offset for the case where there are multiple
elements with the same path. Something like:
function createXPath(el)
{
// Path to element
var tagNames = [el.tagName];
var parent = el.parentNode;
while (parent.nodeType == 1)
{
tagNames.push(parent.tagName);
parent = parent.parentNode;
}
// Element offset
var offset = 0;
var sibling = el.previousSibling;
while (sibling)
{
if (sibling.tagName == el.tagName)
{
offset++;
}
sibling = sibling.previousSibling;
}
return "//" + tagNames.reverse().join("/") + "[" + offset + "]";
}
Jonathan.
On 3/16/06, Matt Labrum <darktempler at gmail.com> wrote:
> function createxPath(e){
>
> var nodes = Array(e.tagName);
> parent = e.parentNode;
>
> while(parent){
>
> nodes[nodes.length] = parent.tagName;
>
> parent = parent.parentNode;
>
> }
>
> nodes = nodes.reverse();
> var xpath = '//';
> for(var i=0;i<nodes .length;i++){
> if(typeof(nodes[i])=='undefined')continue;
> xpath += nodes[i] + '/';
> }
>
> xpath = xpath.substr(0,xpath.length-1);
> return xpath;
>
> }
>
> On 3/16/06, Al <anevare1 at yahoo.com> wrote:
> >
> > Is there a simple technique for obtaining the XPath expression for a
> > clicked-on html dom node? Something similar to the way Platypus creates an
> > XPath to a right-clicked element when it stores a user script. Thanks for
> > your suggestions. Al
> >
> >
> > _______________________________________________
> > Greasemonkey mailing list
> > Greasemonkey at mozdev.org
> > http://mozdev.org/mailman/listinfo/greasemonkey
> >
> _______________________________________________
> Greasemonkey mailing list
> Greasemonkey at mozdev.org
> http://mozdev.org/mailman/listinfo/greasemonkey
>
More information about the Greasemonkey
mailing list