Generate Css path of an element
Full Path Ex:body/footer.Footer/div.Footer-inner/ul.FooterList/li.FooterList_item
function getFullCSSPath(element) {
if (element.tagName == 'HTML') return '';
if (element===document.body) return getShortCSSPath(element);
// To calculate position among siblings
var position = 1;
// Gets all siblings of that element.
// Gets the parent tree node of the current tree node.
var siblings = element.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
var sibling = siblings[i];
// Checks Siblink with passed element.
if (sibling === element) {
var elemCssPath = getShortCSSPath(element);
//console.log('====='+elemCssPath);
//console.log('-----'+position);
return getFullCSSPath(element.parentNode)+'/'+elemCssPath; // using recursion to find its parents untill root element HTML
}
// if it is a siblink & element-node then only increments position.
var type = sibling.nodeType;
if (type === 1 && sibling.tagName === element.tagName) position++;
}
}
Short Path Ex:li.FooterList_item
function getShortCSSPath(element) {
var path = element.tagName.toLowerCase();
if(element.id)
path += "#" + element.id;
if(element.className)
path += "." + element.className;
return path;
}
Test
var elem = document.getElementsByTagName('div')[20];
console.log('Full Path : '+getFullCSSPath(elem));
console.log('Short Path : '+getShortCSSPath(elem));
To generate Xpath