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.
I just wanted to share my version too because it is very clear to understand. I tested this script in all common browsers and it is working like a boss.
TL;DR - this is a more complex problem than it seems and you should use a library.
This problem appears easy at the first glance, but it's trickier than it seems, just as replacing plain URLs with links is non-trivial. Some considerations:
:eq()
limits the usefulness of the solution, as it will require jQueryFurther proof that the problem isn't as easy as it seems: there are 10+ libraries that generate CSS selectors, and the author of one of them has published this comparison.
If you are looking for a comprehensive, non-jQuery solution then you should try axe.utils.getSelector.
Here's a version of Blixt's answer that works in IE:
Following up on what alex wrote. jQuery-GetPath is a great starting point but I have modified it a little to incorporate :eq(), allowing me to distinguish between multiple id-less elements.
Add this before the getPath return line:
This will return a path like "html > body > ul#hello > li.5:eq(1)"
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).