views:

53

answers:

1
+1  A: 

To always get the right element, you will need to use :nth-child() or :nth-type-of() for selectors that do not uniquely identify an element. So try this:

var cssPath = function(el) {
    if (!(el instanceof Element)) return;
    var path = [];
    while (el.nodeType === Node.ELEMENT_NODE) {
        var selector = el.nodeName.toLowerCase();
        if (el.id) {
            selector += '#' + el.id;
        } else {
            var sib = el, nth = 1;
            while (sib.nodeType === Node.ELEMENT_NODE && (sib = sib.previousSibling) && nth++);
            selector += ":nth-child("+nth+")";
        }
        path.unshift(selector);
        el = el.parentNode;
    }
    return path.join(" > ");
}

You could add a routine to check for unique elements in their corresponding context (like TITLE, BASE, CAPTION, etc.).

Gumbo
Yes it looks great. Is it compliant with IE too ?
jney
@jney: If you mean the `:nth-child()` selector, then no.
Gumbo