views:

36

answers:

3

Is there any way to get the text of the selector that invoked some function (if it exists) from within the function?

For example

$('#foo, .bar').click(function() {

   // Here I want to figure out if there was a match on #foo, or .bar

});

Basically I want to have a compounded selector like the one above (http://api.jquery.com/multiple-selector/) but be able to know which one was matched when I get inside the function.

+1  A: 

You can get that info with the event object.

$('#foo, .bar').click(function(event) {

   if(event.target.id === 'foo'){
      alert('foo');
   }
   else if(event.target.className === 'bar'){
      alert('bar');
   }

});

Example: http://www.jsfiddle.net/8CACU/

Ref.: http://api.jquery.com/event.target/

jAndy
Would there be any way to distinguish selectors if you didn't necessarily know what they were beforehand or they were more complex?EG: selector string being constructed programatically or one like $('#foo > .bar > input, '#foo > .boo > input')In a case like that it would require a lot more effort to infer which one was matched.
mrkcsc
@mrkcsc: In your "more complex" example, you still would only look for `event.target.tagName === 'INPUT'`. Your only way to distinguish is over the `event object` since your event handler is attached to each element.
jAndy
Both selectors are on the input tagname though so you would have to do some additional checks to figure out which one of the two it was.I had a feeling this was my only option though and as you say it is pretty much my only choice so I'll mark it as the answer, thanks for the help.
mrkcsc
@mrkcsc: I guess you can avoid this problem completly. Sure, there might be times where you need to figure which element was clicked (but mostly on `event delegation`). I don't know why you need to go this way, but I'm sure you can change your logic/code to avoid it.
jAndy
I can, as I commented originally, I just wanted to do it for performance reasons to minimize the number of times the DOM was searched (through one large compounded selector).
mrkcsc
A: 

$('#foo, .bar').click(GOTEMM(event) {

if(event.target.id === 'foo'){ alert('foo'); } elseif(event.target.className === 'bar'){ alert('bar'); }

notafaggit
A: 

You can use $(this) inside the callback to get the actual element and access the attribute of the element that is used in the selector.

$('#foo, .bar').click(function() { 
    if($(this).attr('id') == 'foo')  {
        alert('foo handled');
    } else if($(this).hasClass('bar')) {
        alert('bar handled');
    }
});

jsfiddle sample: http://jsfiddle.net/us8r9/

Marimuthu Madasamy
Thank you, this is similar solution as posted by jAndy. I was wondering if there was a way to access the selector text directly instead of having to infer it using the this or event object, but it seems not.
mrkcsc