-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
  • 718
  • 2
  • 8
  • 24

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
  • 110,383
  • 23
  • 155
  • 178
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,357
  • 8
  • 29
  • 53
0

If you are using jQuery

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

Using Javascript

document.getElementById("fname").className
prajeesh
  • 1,994
  • 5
  • 27
  • 47