6

This should be basic, but for some reason its not working for me. I just want to store the id when a link that has a certain class is clicked in a variable so as an example:

<a href="#" id="this_id_here" class="only_this_class">Some link</a>

I would want jquery to get the id of the link above and store it in a variable. I have tried $this.attr("id") and $this.id, but non of this worked.

This is what I have for the jquery:

  $(".only_this_class").click(function() {

      var clickedId= $(this).attr("id");
      alert(clickedId);
   });

I just get "undefined" every time.

cbr0wn
  • 361
  • 2
  • 6
  • 15
  • sorry about that. That was not a problem just a typo that I did twice when asking the question. – cbr0wn Aug 28 '11 at 00:48

3 Answers3

4

I removed the space between this and _class in class="only_this _class" and it is working for me.

Try this here

Please have a look at jQuery Selectors

If you have two classes in your HTML then the syntax is different:

$('.classA.classB')

Have a look at How can I select an element with multiple classes?

Community
  • 1
  • 1
Naveed
  • 41,517
  • 32
  • 98
  • 131
  • 1
    ok it actually did work. The problem was that for some reason I ran this at the end of the function before so I guess the id was changed at some point, but when I put this at the beginning I was able to store the id. and thanks for the link to jsfiddle, that sites really useful! – cbr0wn Aug 28 '11 at 00:54
3

NAVEED is right, if you remove the space it works, because if there is a space HTML will put two classes on the element: only_this and _class.

If you are in fact looking for two different classes, you should replace the space with a dot to make it work properly, as in $(".only_this._class")

mu is too short
  • 426,620
  • 70
  • 833
  • 800
gengkev
  • 1,890
  • 2
  • 20
  • 31
0

$(".only_this _class") this selector will look for _class tag in .only_this element. May you are looking for $(".only_this") which will select element which has this class. Try this.

   $(".only_this").click(function() {

      var clickedId= $(this).attr("id");
      alert(clickedId);
   });
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124