-1

I may sound stupid but I am trying to get the value of a class attribute. But it is spitting undefined, while rest of the properties are working fine. I searched on stackoverflow but those are using byClassName or byTagName but I want byElementId JSBIN Link

This is the function

(function() {
  var fname = document.getElementById("fname");
  console.log(fname.id); //fname
  console.log(fname.name); //firstName
  console.log(fname.class); //undefined    
})();

HTML

<input type="text" name="firstName" id="fname" class="gotcha">
fruitjs
  • 745
  • 2
  • 10
  • 25

3 Answers3

2

Use className property to get class

(function() {
  var fname = document.getElementById("fname");
  console.log(fname.id); //fname
  console.log(fname.name); //firstName
  console.log(fname.className); //undefined

})();
<input type="text" name="firstName" id="fname" class="gotcha">
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

(function() {
      var fname = document.getElementById("fname");
      console.log(fname.id); //fname
      console.log(fname.name); //firstName
      console.log(fname.className);
    
    })();
<input type="text" name="firstName" id="fname" class="gotcha">
ozil
  • 6,930
  • 9
  • 33
  • 56
0

If you are using jQuery

$('#fname').attr('class')

Using Javascript

document.getElementById("fname").className
prajeesh
  • 2,202
  • 6
  • 34
  • 59