How can I get selector from jQuery object

How can I get selector from jQuery object

$(this); // how can I get selector from $(this) ?

Is there an easy way to get selector from $(this)? There is a way to select an element by its selector, but what about getting the selector from element?


Solution 1:

Ok, so in a comment above the question asker Fidilip said that what he/she’s really after is to get the path to the current element.

Here’s a script that will “climb” the DOM ancestor tree and then build fairly specific selector including any id or class attributes on the item clicked.

See it working on jsFiddle:

<!DOCTYPE html>
<script src=""></script>
    $(function() {
        $("*").on("click", function(e) {
          var selector = $(this)
            .map(function() { return this.tagName; })

          var id = $(this).attr("id");
          if (id) { 
            selector += "#"+ id;

          var classNames = $(this).attr("class");
          if (classNames) {
            selector += "." + $.trim(classNames).replace(/\s/gi, ".");

<h1><span>I love</span> jQuery</h1>
  <p>It's the <strong>BEST THING</strong> ever</p>
  <button id="myButton">Button test</button>
  <li>Item one
      <li id="sub2" >Sub one</li>
      <li id="sub2" class="subitem otherclass">Sub two</li>

For example, if you were to click the 2nd list nested list item in the HTML below, you would get the following result:


Solution 2:

.selector has been deprecated as of version 1.7, removed as of 1.9

The jQuery object has a selector property I saw when digging in its code yesterday. Don’t know if it’s defined in the docs are how reliable it is (for future proofing). But it works!

$('*').selector // returns *

Edit: If you were to find the selector inside the event, that information should ideally be part of the event itself and not the element because an element could have multiple click events assigned through various selectors. A solution would be to use a wrapper to around bind(), click() etc. to add events instead of adding it directly.

jQuery.fn.addEvent = function(type, handler) {
    this.bind(type, {'selector': this.selector}, handler);

The selector is being passed as an object’s property named selector. Access it as

Let’s try it on some markup (

<p class='info'>some text and <a>a link</a></p>​

$('p a').addEvent('click', function(event) {
    alert(; // p a

Disclaimer: Remember that just as with live() events, the selector property may be invalid if DOM traversal methods are used.

<div><a>a link</a></div>

The code below will NOT work, as live relies on the selector property
which in this case is a.parent() – an invalid selector.

$('a').parent().live(function() { alert('something'); });

Our addEvent method will fire, but you too will see the wrong selector – a.parent().

Solution 3:

In collaboration with @drzaus we’ve come up with the following jQuery plugin.


!(function ($, undefined) {
    /// adapted

    var get_selector = function (element) {
        var pieces = [];

        for (; element && element.tagName !== undefined; element = element.parentNode) {
            if (element.className) {
                var classes = element.className.split(' ');
                for (var i in classes) {
                    if (classes.hasOwnProperty(i) && classes[i]) {
            if ( && !/\s/.test( {
            pieces.unshift(' > ');

        return pieces.slice(1).join('');

    $.fn.getSelector = function (only_one) {
        if (true === only_one) {
            return get_selector(this[0]);
        } else {
            return $.map(this, function (el) {
                return get_selector(el);


Minified Javascript

!function(e,t){var n=function(e){var n=[];for(;e&&e.tagName!==t;e=e.parentNode){if(e.className){var r=e.className.split(" ");for(var i in r){if(r.hasOwnProperty(i)&&r[i]){n.unshift(r[i]);n.unshift(".")}}}if(!/\s/.test({n.unshift(;n.unshift("#")}n.unshift(e.tagName);n.unshift(" > ")}return n.slice(1).join("")};e.fn.getSelector=function(t){if(true===t){return n(this[0])}else{return,function(e){return n(e)})}}}(window.jQuery)

Usage and Gotchas

        <div id="sidebar">
                    <a href="/" id="home">Home</a>
        <div id="main">
            <h1 id="title">Welcome</h1>

        <script type="text/javascript">

            // Simple use case
            $('#main').getSelector();           // => 'HTML > BODY > DIV#main'

            // If there are multiple matches then an array will be returned
            $('body > div').getSelector();      // => ['HTML > BODY > DIV#main', 'HTML > BODY > DIV#sidebar']

            // Passing true to the method will cause it to return the selector for the first match
            $('body > div').getSelector(true);  // => 'HTML > BODY > DIV#main'


Fiddle w/ QUnit tests

Solution 4:

Did you try this ?


Solution 5:

I’ve released a jQuery plugin: jQuery Selectorator, you can get selector like this.

$("*").on("click", function(){
  return false;

Solution 6:

Try this: