Tuesday, May 18, 2010

Get xpath string expression of a document element

XPath is one of those things you don’t hear too much about these days. In the days when XML ruled, XPath was very important to developers as a means of random access within a large structure. Since JSON was popularized, XPath has gotten less and less attention, but there is still fairly good support for XPath queries in browsers.
function getElementXPath(elt)
{
     var path = "";
     for (; elt && elt.nodeType == 1; elt = elt.parentNode)
     {
    idx = getElementIdx(elt);
 xname = elt.tagName;
 if (idx > 1) xname += "[" + idx + "]";
 path = "/" + xname + path;
     }
 
     return path; 
}

function getElementIdx(elt)
{
    var count = 1;
    for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling)
    {
        if(sib.nodeType == 1 && sib.tagName == elt.tagName) count++
    }
    
    return count;
}
http://www.nczonline.net/blog/2009/03/17/xpath-in-javascript-part-1/
http://snippets.dzone.com/posts/show/3754

No comments: