Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getXPathForElement (node, optimized) {
- let Elements = {
- DOMPath: {}
- };
- Elements.DOMPath.xPath=function(node,optimized){if(node.nodeType===Node.DOCUMENT_NODE)
- return'/';const steps=[];let contextNode=node;while(contextNode){const step=Elements.DOMPath._xPathValue(contextNode,optimized);if(!step)
- break;steps.push(step);if(step.optimized)
- break;contextNode=contextNode.parentNode;}
- console.log(steps);
- steps.reverse();return(steps.length&&steps[0].optimized?'':'/')+steps.map(step => step.value).join('/');};
- Elements.DOMPath._xPathValue=function(node,optimized){let ownValue;const ownIndex=Elements.DOMPath._xPathIndex(node);if(ownIndex===-1)
- return null;switch(node.nodeType){case Node.ELEMENT_NODE:if(optimized&&node.getAttribute('id'))
- 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;}
- if(ownIndex>0)
- ownValue+='['+ownIndex+']';return new Elements.DOMPath.Step(ownValue,node.nodeType===Node.DOCUMENT_NODE);};
- Elements.DOMPath._xPathIndex=function(node){function areNodesSimilar(left,right){if(left===right)
- return true;if(left.nodeType===Node.ELEMENT_NODE&&right.nodeType===Node.ELEMENT_NODE)
- return left.localName===right.localName;if(left.nodeType===right.nodeType)
- 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;}
- const siblings=node.parentNode?node.parentNode.children:null;if(!siblings)
- return 0;let hasSameNamedElements;for(let i=0;i<siblings.length;++i){if(areNodesSimilar(node,siblings[i])&&siblings[i]!==node){hasSameNamedElements=true;break;}}
- if(!hasSameNamedElements)
- return 0;let ownIndex=1;for(let i=0;i<siblings.length;++i){if(areNodesSimilar(node,siblings[i])){if(siblings[i]===node)
- return ownIndex;++ownIndex;}}
- return-1;};
- Elements.DOMPath.Step=function (value,optimized) {this.value=value;this.optimized=optimized||false;};
- return Elements.DOMPath.xPath(node, optimized);
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement