Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a jQuery selector for an element

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.

like image 682
Alex Wayne Avatar asked Jan 14 '10 23:01

Alex Wayne


People also ask

How does jQuery select element?

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $().

Can you use CSS selectors in jQuery for selecting elements?

jQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element.

What are jQuery selectors give examples?

For example: $('#real-id') selects a specific element in the document that has an ID of real-id. Tag Class: It represents a tag available with a specific class in the DOM. For example: $('real-class') selects all elements in the document that have a class of real-class.


1 Answers

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)

like image 112
Blixt Avatar answered Sep 23 '22 03:09

Blixt