Andreas Köberle
Andreas Köberle

Reputation: 110892

Get the used selector in an element selected with jquery

Is there a way to get the selector that was used to find an element with jquery? For example I select an element like this:

<span class="test1">lala</span>

a = $('.test1, .test2')

Is there a property in a that holds the .test1 selector string? The only solution I can think about is to ittearte over all selectors and test if they match

var selectors = ['.test1', '.test2'];

a = $(selectors.join(','))

var selector = selectors.find(function(s)return a.is(s))

Upvotes: 1

Views: 73

Answers (3)

Nick Schmidt
Nick Schmidt

Reputation: 1527

It's not that easy. Because the way Anton did it is deprecated. But the event variable contains the selector very hidden.

Have a look at how I achieved it:

$('.test, .test2').on('click', function (e) {
  console.log 'Selector: ', e.currentTarget.classList[0]
}

Here is also a working fiddle: http://jsfiddle.net/fKyZ4/2/

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074208

As Anton mentions, the built-in way to do this was deprecated (for various very good reasons) a while back and has been removed.

The reliable way to do this is:

var sel = ".test";
a = $(sel);
a.data("selector", sel);

If you need to do this a lot, use a function to encapsulate it

function $memo(selector) {
    return $(selector).data("selector", selector);
}
// Usage:
a = $memo(".test");

Then any time you need to know, you can get the selector from data:

var sel = a.data("selector");

Upvotes: 1

Anton
Anton

Reputation: 32581

You could use .selector but it's deprecated in 1.7 and removed in 1.9

console.log(a.selector) //returns .test

Documentation : http://api.jquery.com/selector/

Upvotes: 2

Related Questions