DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jeff has posted 3 posts at DZone. View Full User Profile

Get XPath

07.23.2007
| 13462 views |
  • submit to reddit
        Given a node this will return an array containing the XPath
Usage:

getXPath(document.getElementById('myelement'));

      function getXPath(node, path) {
        path = path || [];
        if(node.parentNode) {
          path = getXPath(node.parentNode, path);
        }

        if(node.previousSibling) {
          var count = 1;
          var sibling = node.previousSibling
          do {
            if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {count++;}
            sibling = sibling.previousSibling;
          } while(sibling);
          if(count == 1) {count = null;}
        } else if(node.nextSibling) {
          var sibling = node.nextSibling;
          do {
            if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {
              var count = 1;
              sibling = null;
            } else {
              var count = null;
              sibling = sibling.previousSibling;
            }
          } while(sibling);
        }

        if(node.nodeType == 1) {
          path.push(node.nodeName.toLowerCase() + (node.id ? "[@id='"+node.id+"']" : count > 0 ? "["+count+"]" : ''));
        }
        return path;
      };

    

Comments

Snippets Manager replied on Thu, 2008/11/27 - 1:44am

have a bug in function eval_xpath() ...var ele=ele.getElementsByTagName(tags[i])[idx-1];... should be: ...var ele=$(ele).children(tags[i])[idx-1];...

Snippets Manager replied on Thu, 2008/11/27 - 1:44am

The inverse function of get_xpath(): function eval_xpath(xpath) {if (document.evaluate) //firefox {return document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; } else //ie {//can not use xmldocument.selectSingleNode(xpath); var tags=xpath.slice(1).split('/'); var ele=document; for (var i=0; i

Snippets Manager replied on Thu, 2008/11/27 - 1:44am

In jQuery, you could do like thus: function get_XPath(elt) {var path = ''; for (; elt && elt.nodeType==1; elt=elt.parentNode) {var idx=$(elt.parentNode).children(elt.tagName).index(elt)+1; idx>1 ? (idx='['+idx+']') : (idx=''); path='/'+elt.tagName.toLowerCase()+idx+path; } return path; } get_XPath(document.getElementsByName('start_price')[0]);