@jcern 的精彩代码的修改版。
特征:
- 如果元素有 id:仅显示
#elementId
- 如果没有 id 存在:显示
element.className
- 如果不存在类:显示附加
element
它innerHtml
(如果有)
- 跳过
<body>
和<html>
元素以缩短输出
- 不依赖 jQuery
function dompath(element) {
var path = '',
i, innerText, tag, selector, classes;
for (i = 0; element && element.nodeType == 1; element = element.parentNode, i++) {
innerText = element.childNodes.length === 0 ? element.innerHTML : '';
tag = element.tagName.toLowerCase();
classes = element.className;
// Skip <html> and <body> tags
if (tag === "html" || tag === "body")
continue;
if (element.id !== '') {
// If element has an ID, use only the ID of the element
selector = '#' + element.id;
// To use this with jQuery, return a path once we have an ID
// as it's no need to look for more parents afterwards.
//return selector + ' ' + path;
} else if (classes.length > 0) {
// If element has classes, use the element tag with the class names appended
selector = tag + '.' + classes.replace(/ /g , ".");
} else {
// If element has neither, print tag with containing text appended (if any)
selector = tag + ((innerText.length > 0) ? ":contains('" + innerText + "')" : "");
}
path = ' ' + selector + path;
}
return path;
}