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, writingthis['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 exconsole.log($(this).attr('class'))
... orhasClass('className')
method to test whether or not your element has a particular class exconsole.log($(this).hasClass('myClassName'))
... 'this.className' still the fastest way to get the whole value – Stphane Commented Apr 12, 2013 at 12:10
3 Answers
Reset to default 9Because 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.