2
<a href="#" class="myclass anotherclass" id="myid anotherid">Link</a>

$('.myclass').click(function () {
    var foo = '';
    alert(foo);
});

In this example, I want an alert to pop up as that says: ".myclass".

How do I alert whatever is entered between the single quotes in the jQuery selector?

EDIT: I want to ONLY alert "myclass". Not "myclass anotherclass"

Derek
  • 5,137
  • 9
  • 28
  • 39

4 Answers4

2

When the click event happens, the jQuery object that was used to bind it no longer exists. Neither the element nor the event handler have any information about the jQuery object that was used. If you want information from the jQuery object, you have to keep it:

var c = $('.myclass');
c.click(function () {
  alert(c.selector);
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

For the delegated handlers you can get the selector property of handleObj property of the event object:

$(document).on('click', '.myclass', function (e) {
    console.log(e.handleObj.selector); // => .myclass
});

But note, that for direct attached handlers the selector will be null and you need to use @Guffa's workaround

$('.myclass').click(function(e) {
    console.log(e.handleObj.selector); // => null  
});
Community
  • 1
  • 1
hazzik
  • 13,019
  • 9
  • 47
  • 86
0

You can try

alert($(this).attr('class'));
George Ant
  • 371
  • 1
  • 6
0

I am assuming you want to get the selector to the object which ever you used for bind the click event. For usual cases $object.selector do your trick but it would not work in even $(this).selector so as a workaround you can send the parameter like below;

var a = $('.myclass')
a.click({sel : a.selector}, function () {
    alert(this.sel);
});
alert($('.myclass').selector)
Onur Topal
  • 3,042
  • 1
  • 24
  • 41