为了始终获得正确的元素,您将需要使用
:nth-child()或
:nth-of-type()来选择不能唯一标识元素的选择器。所以试试这个:
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(" > ");}你可以添加一个例行检查在其对应的背景下独特的元素(如
TITLE,
base,
CAPTION,等)。



