Fawad Ghafoor
Fawad Ghafoor

Reputation: 6207

How to get the class attribute of an element?

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

<a href="http://stackoverflow.com/" 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.com/
       console.log(this.text);            // Click Me
       console.log($("a").prop("class")); // myClassName
   });    
});

Upvotes: 4

Views: 16917

Answers (3)

Anoop
Anoop

Reputation: 23208

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.com/
       console.log(this.text);            // Click Me
       console.log(this.className); // myClassName
   });    
});

Upvotes: 2

VisioN
VisioN

Reputation: 145368

Because it should be this.className instead.

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

Upvotes: 9

Quentin
Quentin

Reputation: 943142

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

Upvotes: 1

Related Questions