Not perfect, but written fast (for You) : )
http://jsfiddle.net/k1qs69fz/7/
Code:
function getCSSPath(el, callback){
var fullPath = '';
var cssPathFn = function (el, callback){
var elPath = '';
elPath = $(el).prop('tagName').toLowerCase();
if(typeof $(el).attr('id') !== 'undefined'){
elPath = elPath+'#'+$(el).attr('id');
}
if(typeof $(el).attr('class') !== 'undefined'){
elPath = elPath+'.'+$(el).attr('class').split(' ').join('.');
}
fullPath = elPath+' '+fullPath;
if(typeof $(el).parent().prop('tagName') !== 'undefined'){
cssPathFn($(el).parent(), callback);
}
else{
callback(fullPath);
}
};
cssPathFn(el, callback);
}
Usage:
getCSSPath($('selector'), callbackFunction);
Function is based on tag
name, id
and class
names, indexes
are not supported.
Sample usage (for HTML code on JSFiddle):
$(document).ready(function (){
getCSSPath($('#lorem-ipsum'), function (path){
console.log(path);
});
});
Sample Result:
html body div#id1.c1.c2.c3 div#id2 div.c4.c5 span span.c6 ul li a span#lorem-ipsum