Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  152] [ 1]  / answers: 1 / hits: 81554  / 13 Years ago, mon, april 18, 2011, 12:00:00

I want to create something like a recorder whichs tracks all actions of a user. For that, i need to identify elements the user interacts with, so that i can refer to these elements in a later session.



Spoken in pseudo-code, i want to be able to do something like the following



Sample HTML (could be of any complexity):



<html>
<body>
<div class=example>
<p>foo</p>
<span><a href=bar>bar</a></span>
</div>
</body>
</html>


User clicks on something, like the link. Now i need to identify the clicked element and save its location in the DOM tree for later usage:



(any element).onclick(function() {
uniqueSelector = $(this).getUniqueSelector();
})


Now, uniqueSelector should be something like (i don't mind if it is xpath or css selector style):



html > body > div.example > span > a


This would provide the possibility to save that selector string and use it at a later time, to replay the actions the user made.



How is that possible?



Update



Got my answer: Getting a jQuery selector for an element


More From » jquery

 Answers
7

I'll answer this myself, because i found a solution which i had to modify. The following script is working and is based on a script of Blixt:



jQuery.fn.extend({
getPath: function () {
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.name;
if (!name) break;
name = name.toLowerCase();

var parent = node.parent();

var sameTagSiblings = parent.children(name);
if (sameTagSiblings.length > 1) {
var allSiblings = parent.children();
var index = allSiblings.index(realNode) + 1;
if (index > 1) {
name += ':nth-child(' + index + ')';
}
}

path = name + (path ? '>' + path : '');
node = parent;
}

return path;
}
});

[#92663] Saturday, April 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaileya

Total Points: 168
Total Questions: 95
Total Answers: 72

Location: Antigua and Barbuda
Member since Sat, Apr 24, 2021
3 Years ago
;