3

With a given jQuery selector $('#my-id .my-class a') stored as a variable jqElement, how can I return the string representation of that selector?

In other words:

jqElement = $('#my-id .my-class a');
jqElement.someFunc(); // returns '#my-id .my-class a'

I looked here How do I get a jQuery selector's expression as text?, but found the information outdated and possibly incomplete.

Community
  • 1
  • 1
jerome
  • 4,809
  • 13
  • 53
  • 70
  • possible duplicate of [How do I get a jQuery selector's expression as text?](http://stackoverflow.com/questions/500246/how-do-i-get-a-jquery-selectors-expression-as-text) – Richard Dalton Sep 08 '11 at 15:33

4 Answers4

3

As provided in the answers to the question you linked to, the selector property is the most appropriate method you'll find.

Whilst it is entirely accurate for basic selectors, you'll find that when using manipulation methods such as parent(), next() etc, the .selector property will get mangled beyond reuse:

alert($('foo[id^=fish]:gt(5):eq(4)').selector); // foo[id^=fish]:gt(5):eq(4)
alert($('foo').children('bar').next().selector); // foo.children(bar).next()

E.g. you can plug the first straight back into $(), but you cannot for the latter.

Matt
  • 74,352
  • 26
  • 153
  • 180
3
$('#my-id .my-class a').selector;
Sahil Muthoo
  • 12,033
  • 2
  • 29
  • 38
2

The selector property exposes a jQuery object's selector. For instance...

var cache = $("#my-id .my-class a");

alert(cache.selector); // will alert "#my-id .my-class a"
cllpse
  • 21,396
  • 37
  • 131
  • 170
2
jqElement.selector

will return selector value

Senad Meškin
  • 13,597
  • 4
  • 37
  • 55