最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the class attribute of an element? - Stack Overflow

programmeradmin3浏览0评论

I want to get the value of the class attribute of an element.

<a href="/" id="myId" class="myClassName">Click Me</a>

this.id, this.href and this.text is working.

My Question is why this.class is not working ?

Note:

I don't want to use:

console.log($this.attr('class')); or console.log($("a").prop("class"));

because its very slow.

$(function(){
   $("a").on("click",function(){
       console.log(this.id);              // myId
       console.log(this.href);            // /
       console.log(this.text);            // Click Me
       console.log($("a").prop("class")); // myClassName
   });    
});

I want to get the value of the class attribute of an element.

<a href="http://stackoverflow./" id="myId" class="myClassName">Click Me</a>

this.id, this.href and this.text is working.

My Question is why this.class is not working ?

Note:

I don't want to use:

console.log($this.attr('class')); or console.log($("a").prop("class"));

because its very slow.

$(function(){
   $("a").on("click",function(){
       console.log(this.id);              // myId
       console.log(this.href);            // http://stackoverflow./
       console.log(this.text);            // Click Me
       console.log($("a").prop("class")); // myClassName
   });    
});
Share Improve this question edited Apr 12, 2013 at 12:11 Nope 22.3k8 gold badges49 silver badges73 bronze badges asked Apr 12, 2013 at 12:02 Fawad GhafoorFawad Ghafoor 6,2177 gold badges43 silver badges54 bronze badges 2
  • 2 Answering the original question: because class is a future reserved word in JS dictionary, one has to always quote it as a property name, writing this['class'] instead. Therefore non-reserved word - className - was used to refer to this attribute instead. – raina77ow Commented Apr 12, 2013 at 12:07
  • 1 Using jquery, you can use attr('class') method to retrieve the class attribute value ex console.log($(this).attr('class')) ... or hasClass('className') method to test whether or not your element has a particular class ex console.log($(this).hasClass('myClassName')) ... 'this.className' still the fastest way to get the whole value – Stphane Commented Apr 12, 2013 at 12:10
Add a ment  | 

3 Answers 3

Reset to default 9

Because it should be this.className instead.

REF: https://developer.mozilla/en-US/docs/DOM/element.className

use this.className it is native javascript element property.

$(function(){
   $("a").on("click",function(){
       console.log(this.id);              // myId
       console.log(this.href);            // http://stackoverflow./
       console.log(this.text);            // Click Me
       console.log(this.className); // myClassName
   });    
});

The class attribute maps onto the className property (not the non-existent class property) in DOM.

发布评论

评论列表(0)

  1. 暂无评论