views:

380

answers:

5

Hi!

 $("*").click(function(){
    $(this); // how can i get selector from $(this) ?
 });

Is there easy way to get selector from $(this) or something like that? There is a way, how to select element by selector, but how about getting selector from element?

Thanx for any help =)

A: 

You can chain the commands, eg:

$(this).$("a").css("display", "none");

This would hide all links which are descendants of the element clicked on.

But why would you want to add an event of type 'click' on EVERY element of your html-page?

henchman
This is just example, i need to get selector from element. I dont need to work with content of that element =(. I hope you undestand me now. I need literarly string, that is the selector =).
Fidilip
A: 

Are you trying to get the name of the current tag that was clicked?

If so, do this..

$("*").click(function(){
    alert($(this)[0].nodeName);
});

You can't really get the "selector", the "selector" in your case is *.

jessegavin
I dont need the tag name. I need just path to the element i clicked.
Fidilip
AH, starting to get somewhere "path to the element" is much different than "selector". SO you need the element, and all its parents node names?
Mark Schultheiss
I have posted another answer which gets more towards your actual goal. You should edit the question so that it is more specific.
jessegavin
A: 

How about:

var selector = "*"
$(selector).click(function() {
    alert(selector);
});

I don't believe jQuery store the selector text that was used. After all, how would that work if you did something like this:

$("div").find("a").click(function() {
    // what would expect the 'selector' to be here?
});
Dean Harding
jQuery internally builds the selector `$('div').find('a').selector` is `div a`. If the events are not created through the jQuery functions, but a wrapper instead, I believe the selector could be passed as the data arguments to the event handler.
Anurag
+1  A: 

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 event.data.selector.

Let's try it on some markup (http://jsfiddle.net/DFh7z/):

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

$('p a').addEvent('click', function(event) {
    alert(event.data.selector); // 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().

Anurag
http://api.jquery.com/selector/
Marko Dumic
I think this is the best what we cen get from jquery =). Maybe i'll find full solution later. Anyway this can be really handy, thx! =)
Fidilip
+3  A: 

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).

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

HTML BODY UL LI UL LI#sub2.subitem.otherclass

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
    $(function() {
      $("*").click(function() {
        var selector = $(this).parents()
                    .map(function() { return this.tagName; })
                    .get().reverse().join(" ");

        if (selector) { 
          selector += " "+ $(this)[0].nodeName;
        }

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

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

        alert(selector);
        return false;
      });
    });
    </script>
</head>
<body>
<h1><span>I love</span> jQuery</h1>
<div>
  <p>It's the <strong>BEST THING</strong> ever</p>
  <button id="myButton">Button test</button>
</div>
<ul>
  <li>Item one
    <ul>
      <li id="sub2" >Sub one</li>
      <li id="sub2" class="subitem otherclass">Sub two</li>
    </ul>
  </li>
</ul>
</body>
</html>
jessegavin