2

This is the HTML in question:

<a href="#" class="a01">xxx a01</a>
<a href="#" class="b02">xxx a021</a>
<a href="#" class="c03">xxx aa021</a>
<a href="#" class="d04">xxx aaa2021</a>

On click on a link, jQuery:

$("a").click(function(){
   alert($(this).html()); // we get xxx a01 , xxx a021 and so on..
})

How do I get the class value, such as a01, b02, c03 and so on?

thanks.

luvieere
  • 37,065
  • 18
  • 127
  • 179
danky pang
  • 31
  • 1

3 Answers3

5

Use this.className, it's faster and less redundant than $(this).attr("class").

$("a").click(function(){
    alert(this.className);
});


Most attributes are directly accessible as properties of the element, so wrapping jQuery around this and using attr() or prop() are generally unnecessary.

Read more on this at http://whattheheadsaid.com/2010/10/utilizing-the-awesome-power-of-jquery-to-access-properties-of-an-element (plug).

Andy E
  • 338,112
  • 86
  • 474
  • 445
2

You can use jQuery's .attr() method in order to retrieve any attribute from an element.

$(this).attr("class")
Jeremy
  • 1
  • 85
  • 340
  • 366
  • @dankypang: Once you've got answers that solve your problem, you may chose to select the best one as the "accepted answer" by clicking the grey checkmark beside it. – Jeremy Aug 27 '11 at 09:29
  • I'd use `.prop()` rather then `.attr()` for classname. – Madara's Ghost Aug 27 '11 at 09:33
  • @RikudoSennin: I'm not sure I understand it, but I think that `.attr("class")` should be equivalent to `.prop("className")`. – Jeremy Aug 27 '11 at 09:37
1
alert($(this).attr('class'));

http://api.jquery.com/attr/

Emil
  • 8,449
  • 3
  • 27
  • 44