3

I have a radio button, and when it is pressed a function is called, which accepts the class of the button as an argument. So something like this:

<input class="myclass" type="radio" name="name" value="x" checked="true" onClick="myFunction(this.value, this.getAttribute('class'))"></input>

Notice that in my onClick, I have this.getAttribute('class') instead of simply this.class. I tried using this.class but I kept getting undefined. Is this.class not an acceptable thing to do? I have used this.id elsewhere in my code which works fine, but for some reason I need to use getAttribute when I want to reference class.

So essentially I am asking what is the difference between this.class and this.getAttribute('class')?

pwerth
  • 190
  • 1
  • 2
  • 13
  • 12
    `this.class` is incorrect; you intended to access `this.className`. – Jon Aug 18 '14 at 15:23
  • Or `classList`: https://developer.mozilla.org/en-US/docs/Web/API/element.classList – jgillich Aug 18 '14 at 15:25
  • `getAttribute` looks for HTML attributes. Using `this.class` looks for a JS attribute, which does not exist. The JS equivalent of the HTML `class` attribute is `className`. `class` is also a reserved keyword in JavaScript, so avoid using it. – SeinopSys Aug 18 '14 at 15:25
  • 1
    possible duplicate of [HTML - attributes vs properties](http://stackoverflow.com/questions/19246714/html-attributes-vs-properties) – Oriol Aug 18 '14 at 15:28
  • thanks all - this.className is indeed what I wanted – pwerth Aug 18 '14 at 15:44

2 Answers2

3

There is no this.class. i think you mean this.className. see this:

getAttribute("class") is more universal, because it can be used in different types of documents. In XML documents, most importantly. Including SVG.

this.className works only in HTML

Brokkoli 71
  • 141
  • 8
Suchit kumar
  • 11,448
  • 3
  • 17
  • 41
2

Use className to get the current value of the class attribute. I think the reason behind this is because class is a reserved word.

E. Sundin
  • 3,658
  • 16
  • 27