views:

237

answers:

2

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.

+2  A: 

jQuery-GetPath is a good starting point: it'll give you the item's ancestors, like this:

var path = $('#foo').getPath();
// e.g., "html > body > div#bar > ul#abc.def.ghi > li#foo"
Agos
+4  A: 
Blixt
jQuery has a built-in `index` function that can take care of the loop part. Just say `var i = siblings.index(node)` and that ought to work.
Dan
I changed it so that it'll stop once it finds an element with an ID, and will also use class names to narrow down the elements: http://paste.blixt.org/297640
Blixt
@Dan: Ah, I had a feeling there'd be something like that, thanks =)
Blixt