[英]How to get the class attribute of an element?
我想獲取元素的class屬性的值。
<a href="http://stackoverflow.com/" id="myId" class="myClassName">Click Me</a>
this.id
, this.href
和this.text
工作。
我的問題是為什么this.class
無法正常工作?
注意:
我不想使用:
console.log($this.attr('class'));
或console.log($("a").prop("class"));
因為它很慢。
$(function(){
$("a").on("click",function(){
console.log(this.id); // myId
console.log(this.href); // http://stackoverflow.com/
console.log(this.text); // Click Me
console.log($("a").prop("class")); // myClassName
});
});
因為它應該是this.className
代替。
參考: https : //developer.mozilla.org/en-US/docs/DOM/element.className
使用this.className
是本機javascript元素屬性。
$(function(){
$("a").on("click",function(){
console.log(this.id); // myId
console.log(this.href); // http://stackoverflow.com/
console.log(this.text); // Click Me
console.log(this.className); // myClassName
});
});
class
屬性映射到DOM中的className
屬性(不是不存在的class
屬性)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.