Guest User

Untitled

a guest
Oct 18th, 2019
75
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function getXPathForElement (node, optimized) {
  2.  
  3. let Elements = {
  4. DOMPath: {}
  5. };
  6.  
  7. Elements.DOMPath.xPath=function(node,optimized){if(node.nodeType===Node.DOCUMENT_NODE)
  8. return'/';const steps=[];let contextNode=node;while(contextNode){const step=Elements.DOMPath._xPathValue(contextNode,optimized);if(!step)
  9. break;steps.push(step);if(step.optimized)
  10. break;contextNode=contextNode.parentNode;}
  11. console.log(steps);
  12. steps.reverse();return(steps.length&&steps[0].optimized?'':'/')+steps.map(step => step.value).join('/');};
  13.  
  14. Elements.DOMPath._xPathValue=function(node,optimized){let ownValue;const ownIndex=Elements.DOMPath._xPathIndex(node);if(ownIndex===-1)
  15. return null;switch(node.nodeType){case Node.ELEMENT_NODE:if(optimized&&node.getAttribute('id'))
  16. return new Elements.DOMPath.Step('//*[@id="'+node.getAttribute('id')+'"]',true);ownValue=node.localName;break;case Node.ATTRIBUTE_NODE:ownValue='@'+node.nodeName();break;case Node.TEXT_NODE:case Node.CDATA_SECTION_NODE:ownValue='text()';break;case Node.PROCESSING_INSTRUCTION_NODE:ownValue='processing-instruction()';break;case Node.COMMENT_NODE:ownValue='comment()';break;case Node.DOCUMENT_NODE:ownValue='';break;default:ownValue='';break;}
  17. if(ownIndex>0)
  18. ownValue+='['+ownIndex+']';return new Elements.DOMPath.Step(ownValue,node.nodeType===Node.DOCUMENT_NODE);};
  19.  
  20. Elements.DOMPath._xPathIndex=function(node){function areNodesSimilar(left,right){if(left===right)
  21. return true;if(left.nodeType===Node.ELEMENT_NODE&&right.nodeType===Node.ELEMENT_NODE)
  22. return left.localName===right.localName;if(left.nodeType===right.nodeType)
  23. return true;const leftType=left.nodeType===Node.CDATA_SECTION_NODE?Node.TEXT_NODE:left.nodeType;const rightType=right.nodeType===Node.CDATA_SECTION_NODE?Node.TEXT_NODE:right.nodeType;return leftType===rightType;}
  24. const siblings=node.parentNode?node.parentNode.children:null;if(!siblings)
  25. return 0;let hasSameNamedElements;for(let i=0;i<siblings.length;++i){if(areNodesSimilar(node,siblings[i])&&siblings[i]!==node){hasSameNamedElements=true;break;}}
  26. if(!hasSameNamedElements)
  27. return 0;let ownIndex=1;for(let i=0;i<siblings.length;++i){if(areNodesSimilar(node,siblings[i])){if(siblings[i]===node)
  28. return ownIndex;++ownIndex;}}
  29. return-1;};
  30.  
  31. Elements.DOMPath.Step=function (value,optimized) {this.value=value;this.optimized=optimized||false;};
  32.  
  33. return Elements.DOMPath.xPath(node, optimized);
  34. };
RAW Paste Data