2

In JavaScript, supposing I have a reference to an element, how do I retrieve an XPath expression that would select it?

Is there something like objElement.xpath?

Shog9
  • 156,901
  • 35
  • 231
  • 235
Annibigi
  • 5,895
  • 5
  • 23
  • 21

2 Answers2

2

Since Annibigi doesn't want to post the solution, I'll do it: See this snippet.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
0

This is not XPATH related, but just to show you how you can get the parent/child relationship with a damn simple while loop.

var pathAt = function(node) {
    var stack = [];
    while(node.parentNode !== null) {
        stack.unshift(node.tagName);
        node = node.parentNode;
    }
    return stack.join('/');
}

// Usage : pathAt(document.getElementBy('moo'));
// Outputs : "HTML/BODY/CENTER/TABLE/TBODY/TR/TD/TABLE/TBODY/TR/TD/TABLE/TBODY/TR/TD/TABLE/TBODY/TR/TD"
Christophe Eblé
  • 8,071
  • 3
  • 33
  • 32