Perhaps 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 modified a method from another question to go through, and add in the full text contents of the tag via a :contains()
operator only if the tag has no children tags.
I had tested with 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 clicking on p then get output as:
html body div ul li:contains('hi')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…