我有这个功能,它返回我的路径el
。但是,有时此功能会添加页面上不存在的元素。在这种情况下:
<table>
<tr><td></td><tr>
</table>
td 的路径看起来像table > tbody > tr > td
。这个功能有什么问题?
function getDomPath(el) {
element = el;
if (!(el instanceof Element)) return;
var path = [];
while (el.nodeType === Node.ELEMENT_NODE && el.id != "jobs") {
var selector = el.nodeName.toLowerCase();
if (el.id) {
selector += '#' + el.id;
}
else if(el.className){
console.log(el.className);
selector += '.' + el.className;
}
else {
var sib = el, nth = 1, count = 1;
while (sib.nodeType === Node.ELEMENT_NODE && (sib = sib.previousSibling) && nth++){
console.log(Node.ELEMENT_NODE)
console.log(el.previousSibling);
console.log(el);
count += $(el).prevAll().size();
};
selector += ":nth-child("+count+")";
}
path.unshift(selector);
el = el.parentNode;
}
return path.join(" > ");
};