For the following project I will be using PHP and jQuery.
I have the following code:
$(\'*\').onclick(function(){
});
Once a user
You can use the .parents() method, to get all ancestors of the clicked element.
$(document).delegate('*','click',function(){
var path = $(this).parents().andSelf();
return false;
});
and then extract the info you want.
Use the .delegate method to handle the event, so you do not need to attach it to all elements. And also use the .andSelf() method to include in the path the item that was clicked as well.
A more complete example
$(document).delegate('*','click',function(){
var path = $(this).parents().andSelf();
var xpath='/';
for (var i = 0; i < path.length; i++)
{
var nd = path[i].nodeName.toLowerCase();
xpath += '/';
if (nd != 'html' && nd != 'body')
{xpath += nd+'['+ ($(path[i-1]).children().index(path[i])+1) +']';}
else
{xpath += nd;}
}
alert(xpath);
return false;
});
Example with a test html to play at http://www.jsfiddle.net/gaby/hsv97/1/
update with id
and class
shown as well : http://www.jsfiddle.net/gaby/hsv97/2/
a fix to Gaby aka G. Petrioli
added "nd" to children
.children(nd)
full:
$(document).delegate('*','click',function(){
var path = $(this).parents().andSelf();
var xpath=''; // firebug xpath starts with '/html'
for (var i = 0; i < path.length; i++) {
var nd = path[i].nodeName.toLowerCase();
if (nd =="tbody") continue; // php DOMxpath ignores tbody? or browser fixes html?
xpath += '/';
if (nd != 'html' && nd != 'body')
{xpath += nd+'['+ ($(path[i-1]).children(nd).index(path[i])+1) +']';} //! saving time ha?
else
{xpath += nd;}
}
alert(xpath);
return false;
});