3

I am currently learning javascript and I found some difficulties in understanding the difference between class and className.

I am wondering if there are any difference between class and className. As when I am learning Javascript, I found that I may use either of it to retrieve the class name of specific node: e.g.

   var firstChildClass = firstChildName.className; 
   var firstChildClass2 = firstChildName.getAttribute('class')

A more detailed script can be found on http://jsfiddle.net/hphchan/3ze3ug7r/.

I would like to ask in implementation, are there any subtle differences between the two?

Btw I have been visited object.className or object.getAttribute("className/class")?, and understand that using getAttribute('class') is more universal than className since className works only on HTML, not others like SVG. But are any extra difference exist between the two?

Thanks.

Community
  • 1
  • 1
CHANist
  • 1,302
  • 11
  • 36
  • No other differences, just the problem of 'class' and 'className' in legacy browsers, and generality for markup other than HTML. – Peter Olson Jul 08 '15 at 08:25
  • 3
    They are not the same. One is a getter/setter and one directly grabs the value out from HTML. [They can return different values.](http://jsfiddle.net/DerekL/wgfkhdb8/) – Derek 朕會功夫 Jul 08 '15 at 08:27
  • You should also consider [classList](https://developer.mozilla.org/en/docs/Web/API/Element/classList) when talking about class retrieval differences. – dakab Jul 08 '15 at 08:59

1 Answers1

0

As @Derek-朕會功夫 stated, the getAttribute is onlt used to retrieve the value of the class attribute while accessing directly the className attribute allows to get & set the class names.

Furhtermore, the getAttribute function works with any kind of attribute and could be use to easily retrieve values dynamically eg getAttribute(attributeName).

POZ
  • 583
  • 4
  • 11