danky pang
danky pang

Reputation: 31

How to select class properties via jQuery

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.

Upvotes: 2

Views: 116

Answers (3)

Emil
Emil

Reputation: 8527

alert($(this).attr('class'));

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

Upvotes: 1

Andy E
Andy E

Reputation: 344517

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

Upvotes: 5

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

$(this).attr("class")

Upvotes: 2

Related Questions