crunchit
Version:
Autotrack the events from your users
50 lines (42 loc) • 1.39 kB
JavaScript
function getElementXPath(element) {
let paths = [];
for (; element && element.nodeType == 1; element = element.parentNode) {
let index = 0;
for (
let sibling = element.previousSibling;
sibling;
sibling = sibling.previousSibling
) {
if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) {
continue;
}
if (sibling.nodeName == element.nodeName) {
++index;
}
}
let tagName = element.nodeName.toLowerCase();
let pathIndex = index ? "[" + (index + 1) + "]" : "";
// ! Find associated text content.
let textContent = "";
// ! Check if the current node is a text or not.
if (element.nodeType === Node.TEXT_NODE) {
textContent = element.textContent.trim();
} else {
// ! Check for direct child text nodes only.
for (let child of element.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
textContent += child.textContent.trim();
}
}
}
// ! Limit the textContent to 20 characters.
if (textContent.length > 20) {
textContent = textContent.substring(0, 20) + "...";
}
let nodeWithText =
textContent && tagName !== "html" ? "{" + textContent + "}" : "";
paths.splice(0, 0, tagName + pathIndex + nodeWithText);
}
return paths.length ? "/" + paths.join("/") : null;
}
module.exports = getElementXPath;