开发者

How to select class properties via jQuery

开发者 https://www.devze.com 2023-03-31 08:14 出处:网络
This is the HTML in question: <a href=\"#\" cla开发者_StackOverflow中文版ss=\"a01\">xxx a01</a>

This is the HTML in question:

<a href="#" cla开发者_StackOverflow中文版ss="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.


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

$("a").click(function(){
    alert(this.className);
});
  • element.className - Mozilla Developer Network


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


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

$(this).attr("class")


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号