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
2010-09-01 16:55:00