1

I have created a javascript function which on click of any element in the page gives the Xpath of that element and all attributes of that element. This part is done.Now i want to use this function as a utility and should work on any web application. is there any way to do this? please sugeest me. below is the JS function:

  <script>
document.onclick= function(event) {
    if (event===undefined) event= window.event;                    
      var target= 'target' in event? event.target : event.srcElement; 
    var path= getPathTo(target);
    var attList = getAllAttributes(target);
    console.log(path);
};   
 function getPathTo(element) {
    if (element.id!=='')
        return "//*[@id='"+element.id+"']";

    if (element===document.body)
        return element.tagName.toLowerCase();

    var ix= 0;
    var siblings= element.parentNode.childNodes;
    for (var i= 0; i<siblings.length; i++) {
        var sibling= siblings[i];

        if (sibling===element) return getPathTo(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';

        if (sibling.nodeType===1 && sibling.tagName === element.tagName) {
            ix++;
        }
    }
};     
function getAllAttributes(element){
    var arr=[];
    var attrs = element.attributes;
    for (var i = 0; i < attrs.length; i++) {
        arr.push({ AttributeName:attrs[i].name, Value:attrs[i].value});
}
    console.log(arr);
}
</script>
newtextJS
  • 45
  • 1
  • 6
  • Move your utility functions to a separate js file and import that file when you need it: ``. – Shanoor Dec 22 '15 at 08:01
  • actually thing is this utility is for testing team. they will not have the codebase so they wont be able to include script directly. there is a testing Web UI, where i need to add some button on click of which this JS can be invoked. And it will start working once i click DOM elements on that page. – newtextJS Dec 22 '15 at 08:10
  • You can load script dynamically: http://stackoverflow.com/questions/5830430/dynamically-load-javascript-with-javascript Either copy/paste the code inside your button's click or host the script in accessible local server. – Shanoor Dec 22 '15 at 08:19

0 Answers0