[Greasemonkey] generating XPath string from dom node

Jonathan Buchanan jonathan.buchanan at gmail.com
Thu Mar 16 16:40:38 EST 2006


Naturally, I didn't realise that until about 5 seconds after I'd hit Send :-)

Since we're going right to the root, I suppose the double forward
slash could be omitted as well?

function createXPath(el)
{
    var path = [tagNameWithOffset(el)];
    var parent = el.parentNode;
    while (parent.nodeType == 1)
    {
        path.push(tagNameWithOffset(parent));
        parent = parent.parentNode;
    }

    return "/" + path.reverse().join("/");
}

function tagNameWithOffset(el)
{
    var offset = 0;
    var sibling = el.previousSibling;
    while (sibling)
    {
        if (sibling.tagName == el.tagName)
        {
            offset++;
        }
        sibling = sibling.previousSibling;
    }
    return el.tagName + "[" + offset + "]";
}

On 3/16/06, Jeremy Dunck <jdunck at gmail.com> wrote:
> On 3/16/06, Jonathan Buchanan <jonathan.buchanan at gmail.com> wrote:
> > 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:
> >
> ...
> >     return "//" + tagNames.reverse().join("/") + "[" + offset + "]";
>
> You'll want to find the offset for each tag, not just the leaf.
> _______________________________________________
> Greasemonkey mailing list
> Greasemonkey at mozdev.org
> http://mozdev.org/mailman/listinfo/greasemonkey
>


More information about the Greasemonkey mailing list