Trying to get class name from tr tag - 'undefined'

10,417

Solution 1

element.class is incorrect.

You need to use element.className.

https://developer.mozilla.org/en-US/docs/DOM/element.className

Solution 2

It's classname, not class.

alert(tr_id + ' ' + document.getElementById(tr_id).className);

jsFiddle example

See: https://developer.mozilla.org/en-US/docs/DOM/element.className

Solution 3

Use className instead of class jsfiddle

 <script language='javascript'>
  function info(theElement, id)
     {
         tr_id = 'cat_' + id;
         alert(tr_id + ' ' + document.getElementById(tr_id).className);
     }
 </script>

Solution 4

Use

document.getElementById(tr_id).className

or for modern browsers which support DOMTokenList:

var d = document.getElementById(tr_id).classList
// d[0] would return class_a

Solution 5

Use className instead of class

document.getElementById(tr_id).className
Share:
10,417
a coder
Author by

a coder

SOreadytohelp

Updated on June 14, 2022

Comments

  • a coder
    a coder about 2 years

    I need to get the class name from a given <tr> tag, but am unable to do so.

    <table cellpadding=5 cellspacing=5>
        <tr id='cat_abc123' class='class_a'>
            <td>foo</td>
            <td><input type='checkbox' name='cb1' value='1' onClick="info(this, 'abc123')">
        </tr>
    </table>
    
     <script language='javascript'>
         function info(theElement, id)
         {
             tr_id = 'cat_' + id;
             alert(tr_id + ' ' + document.getElementById(tr_id).class);
         }
     </script>
    

    Working example: http://jsfiddle.net/rQpeu/

    What am I missing?

    Update

    I was using the wrong descriptor - should use Classname. Thanks for the prompt responses everyone! Updated jsfiddle: http://jsfiddle.net/rQpeu/3/