Maybe something like this:
function dompath( element ) { var path = ''; for ( ; element && element.nodeType == 1; element = element.parentNode ) { var inner = $(element).children().length == 0 ? $(element).text() : ''; var eleSelector = element.tagName.toLowerCase() + ((inner.length > 0) ? ':contains(\'' + inner + '\')' : ''); path = ' ' + eleSelector + path; } return path; }
This changed the method from another question to go through and add the full text content of the tag using the operator :contains() only if the tag has no tags for children.
I tested this method:
$(document).ready(function(){ $('#p').click(function() { console.log(dompath(this)); }); });
Against this:
<html> <body> <div> <div> </div> </div> <ul> <li></li> <li></li> </ul> <div> <ul> <li id="p">hi</li> <li></li> <li id="p2">hello world</li> </ul> </div> <body> <html>
The results of pressing p are then output as:
html body div ul li: contains ('hi')
source share