Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
   });    
});
like image 271
Fawad Ghafoor Avatar asked Oct 23 '25 08:10

Fawad Ghafoor


2 Answers

Because it should be this.className instead.

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

like image 89
VisioN Avatar answered Oct 25 '25 22:10

VisioN


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
   });    
});
like image 43
Anoop Avatar answered Oct 25 '25 21:10

Anoop