DDEX
DDEX

Reputation: 455

Adding row to a table with Javascript

I am just doing a Javascript excercise which should add a row into a table. Html reads like this:

<!DOCTYPE html>  
<html><head><br><meta charset=utf-8 />   
</head><body>  
<table id="sampleTable" border="1">  
<tr><td>Row1 cell1</td>  
<td>Row1 cell2</td></tr>  
<tr><td>Row2 cell1</td>  
<td>Row2 cell2</td></tr>  
</table><br>  
<input type="button" onclick="insert_Row()" value="Insert row">   
</body></html>  

And my script that doesn't work:

 function insert_Row(){
      var xTable=document.getElementById('sampleTable');
       for (i=0;i<=xTable.children.length;i++)
       {
        if(i===xTable.children.length)
        {
          xTable.createElement('tr');
          tr.innerHTML ='<td>cell1</td><td>cell2</td>'

        }

      }

    }

This is the correct solution:

function insert_Row()
{
var x=document.getElementById('sampleTable').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML="New Cell1";
z.innerHTML="New Cell2";
}

I would like to understand what is wrong with my first solution? Why doesn't it create the tag but throws error instead?

Upvotes: 2

Views: 13479

Answers (4)

AL-zami
AL-zami

Reputation: 9066

your xTable.createElement is not creating any child element.The actual method is document.createElement().There is no element.createElement

again parentnode.children is accessing only the elements which is a direct children of table element which is tBody element.So, parentnode.children.length is equal to 1 here.But it will increase after adding another tr element as it was not added to tbody element.Thus it makes the for loop infinite.I will discuss it shortly.

also you have to use element.appendChild() method to appedn the child you have already created.To add table cells don't use innerHTML,rather use dom methods to do this things for you

The for loop in your code is getting infinite, because after adding one tr element to your table, xTable.children.length is increased by one.So,every time the for loop is executed it finds that the length is increased and after adding another tr element it increases once again. So,it never gets any chance to break.Thus become infinite loop.So careful when using for loop to add element to table

  var xTable=document.getElementById('sampleTable');

      var tr=document.createElement('tr');
      tr.innerHTML ='<td>cell1</td><td>cell2</td>'
      xTable.appendChild(tr);

Upvotes: 5

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201528

The first error, in execution, is that you try to call xTable.createElement. Element nodes do have a createElement method; document nodes do, so you would need to use document.createElement('tr') instead. And you need to assign its return value to a variable in order to do anything with the newly created element.

Moreover, you need to add the element to the document tree. If you add it to the table, there is a problem. You have loop that traverses all the children of the table, and appending a new child would make the loop infinite. The loop is actually not needed at all. To find the last child, you need not traverse all children; you just use the children.length property. But you don’t need even that; to append a row (which is what you are doing here, not really inserting), you simply call the appendChild method of the prospective parent.

There’s more. In HTML (strictly speaking, in HTML linearization only, not in XHTML linearization), a tr element is not a child of table. Browsers will insert tbody elements when needed so that a tr is a child of a tbody which is a child of table. This means that the value of xTable.children.length is 1; the table has just one child, a tbody element.

Thus, using the approach in your first code can be properly coded as follows:

<table id="sampleTable" border="1">  
<tr><td>Row1 cell1</td>  
<td>Row1 cell2</td></tr>  
<tr><td>Row2 cell1</td>  
<td>Row2 cell2</td></tr>  
</table>
<p><input type="button" onclick="insert_Row()" value="Insert row">   
<script>
 function insert_Row(){
      var xTable = document.getElementById('sampleTable');
      var tr = document.createElement('tr');
      tr.innerHTML = '<td>cell1</td><td>cell2</td>';
      xTable.children[0].appendChild(tr); // appends to the tbody element
}
</script>

Upvotes: 2

Rudie
Rudie

Reputation: 53781

Tables are special. They have special (optional) methods to add children. TABLE has insertRow and TR has insertCell. They're especially useful if you want to add the row/cell somewhere not at the end.

Setting a TR's innerHTML should work on most browsers, but probably not all.

(If you're building an entire table, create the HTML in JS and then set an innerHTML. It's much faster than creating separate TR and TD.)

Upvotes: 0

epascarello
epascarello

Reputation: 207501

You never add the row to the table. The createElement does not attach itself to anything. You would need to use appendChild() or insertBefore()

var table = document.getElementById("sampleTable"),
    tbody = table.getElementsByTagName("tbody")[0];

for (var i=0;i<5;i++) {
  var row = document.createElement("tr");
  var cell1 = document.createElement("td");
  var cell2 = document.createElement("td");
  cell1.innerHTML = i + "- 1";
  cell2.innerHTML = i + "- 2";
  row.appendChild(cell1);
  row.appendChild(cell2);
  tbody.appendChild(row);  
}
<table id="sampleTable" border="1">
  <tbody>
    <tr>
      <td>Row1 cell1</td>
      <td>Row1 cell2</td>
    </tr>
    <tr>
      <td>Row2 cell1</td>
      <td>Row2 cell2</td>
    </tr>
  </tbody>
</table>

Upvotes: 6

Related Questions