Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  86] [ 4]  / answers: 1 / hits: 39201  / 15 Years ago, thu, january 14, 2010, 12:00:00

In psuedo code, this is what I want.



var selector = $(this).cssSelectorAsString(); // Made up method...
// selector is now something like: html>body>ul>li>img[3]
var element = $(selector);


The reason is that I need to pass this off to an external environment, where a string is my only way to exchange data. This external environment then needs to send back a result, along with what element to update. So I need to be able to serialize a unique CSS selector for every element on the page.



I noticed jquery has a selector method, but it does not appear to work in this context. It only works if the object was created with a selector. It does not work if the object was created with an HTML node object.


More From » jquery

 Answers
2

I see now that a plugin existed (with the same name I thought of too), but here's just some quick JavaScript I wrote. It takes no consideration to the ids or classes of elements – only the structure (and adds :eq(x) where a node name is ambiguous).


jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';

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 siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}

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

return path;
};

(License: MIT)


[#97826] Tuesday, January 12, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braidenv

Total Points: 80
Total Questions: 104
Total Answers: 91

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
;