0

I need to get the XPath expression when I click on an element in a HTML page. This solution is very helpful: https://stackoverflow.com/a/5178132/1718124

function createXPathFromElement(elm) { 
var allNodes = document.getElementsByTagName('*'); 
for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) 
{ 
    if (elm.hasAttribute('id')) { 
            var uniqueIdCount = 0; 
            for (var n=0;n < allNodes.length;n++) { 
                if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++; 
                if (uniqueIdCount > 1) break; 
            }; 
            if ( uniqueIdCount == 1) { 
                segs.unshift('id("' + elm.getAttribute('id') + '")'); 
                return segs.join('/'); 
            } else { 
                segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]'); 
            } 
    } else if (elm.hasAttribute('class')) { 
        segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]'); 
    } else { 
        for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) { 
            if (sib.localName == elm.localName)  i++; }; 
            segs.unshift(elm.localName.toLowerCase() + '[' + i + ']'); 
    }; 
}; 
return segs.length ? '/' + segs.join('/') : null; 
};

The javascript mentioned above returns the following XPath for a link on the main page of stackoverflow:

id("question-summary-21052053")/div[@class="summary"]/h3[1]/a[@class="question-hyperlink"]

But I need a list of all links like this XPath:

.//*/div[@class="summary"]/h3[1]/a[@class="question-hyperlink"]

How do I have to change the above Javascript code to return the XPath above? The XPath must work with the HtmlAgilityPack.

Thank you very much!

Community
  • 1
  • 1
jimbo
  • 582
  • 1
  • 11
  • 28

1 Answers1

0

using jQuery try this...

var elements = $("#question-summary-21052053 div[class='summary'] h3:first a[class='question-hyperlink']");
xspydr
  • 3,030
  • 3
  • 31
  • 49
  • Don't know how this can help me. I need to get a XPath from a Javascript function like mentioned above. I have edited the question again to make a more clear. – jimbo Jan 11 '14 at 12:11