Adding the Row dynamically to the table

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • romepatel
    New Member
    • Nov 2009
    • 31

    Adding the Row dynamically to the table

    Hello,

    I am adding a row dynamically to the table ,

    Code:
    var table = document.getElementById('example');
    var rowCount  = table.rows.length;
    var row = table.insertRow(rowCount);
    now i want to set attributes to the new row added such as id, class etc

    How can i do that.

    Please help

    Thanks in advance
    Last edited by Dormilich; Dec 28 '09, 11:39 AM. Reason: Please use [code] tags when posting code
  • RamananKalirajan
    Contributor
    • Mar 2008
    • 608

    #2
    Hi...
    This will help you out

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Its important to define the DocType for HTML -->
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script type="text/javascript">
    var counter=0;
    function doThis()
    {
       var tempId = "Count"+counter;
       var x = document.getElementById('myText').value
       var xx= "<input type='text' value='"+x+"' id='"+tempId+"' onclick='alert(this.parentNode.parentNode.id)'>";
       var row=document.getElementById('myTable').rows.length; 
       var y=document.getElementById('myTable').insertRow(row)  ;
       y.id="rowId"+row;
       counter++;
       var b=y.insertCell(0);
       b.innerHTML=xx; 
        
    }
    </script>
    </head>
    <body>
    <input type="text" id="myText">
    <br/>
    <input type="button" value="Add" onclick="doThis()">
    <br/>
    <table id="myTable" border="1" cellspacing="5" cellpadding="5">
    <tr>
    <th>Name</th>
    </tr>
    </table>  
    </body>
    </html>
    Thanks and Regards
    Ramanan Kalirajan

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      You can use elem.id and elem.className as shown in RK's code, or use setAttribute().

      Comment

      Working...