Saturday, February 5, 2011

How might I determine the XPath of a DOM element?

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?

  • 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"
    
    Aaron Digulla : You also need to include the index for elements which can appear multiple times as a child (think DIV or P).
    From SleepyCod
  • Since Annibigi doesn't want to post the solution, I'll do it: See this snippet.

0 comments:

Post a Comment