views:

32

answers:

2

From what I gather, tBodies[0] seems to work in IE, but not FF. Is this an IE mistake? I've created a small file to demonstrate the incosistency, and I would like to know the best way to go about this.

The HTML:

<html>
<body>
 <table id="dataGrid">
 </table>
 <input type="button" onclick="insertRow();" value="New row">
</body>
</html>

This script should add a row every time the button is clicked. It works in IE but breaks in Firefox:

<script type="text/javascript" src="/costplan/script/prototype.js"></script>
<script>    
function insertRow(){
 var objTbl = $('dataGrid').tBodies[0]; 
 lastRow = objTbl.rows.length;
 alert(lastRow);
 var newRow = objTbl.insertRow(lastRow);
}
</script>

Is tBodies[0] invalid? I'm not sure why, but this code works in both FF and IE:

<script type="text/javascript" src="/costplan/script/prototype.js"></script>
<script>
function insertRow(){
 var objTbl = $('dataGrid');
 lastRow = objTbl.rows.length;
 alert(lastRow);
 var newRow = objTbl.insertRow(lastRow);
}    
</script>

Are either of these functions correct? Basically, I don't really know what's going on (I gather that at least one of these scripts is invalid, but I don't know which or why).

+1  A: 

The tBodies property is part of the DOM Level 2 standard, and it works on both browsers.

The difference you are having is that IE always injects a TBODY element as a child of your empty table.

Firefox, Chrome and other browsers don't do it if the element is empty, if the TABLE element has at least one TR or TH, they will create the TBODY implicitly.

You could add the TBODY element by yourself, and your example will work without problems:

<table id="dataGrid">
  <tbody>
  </tbody>
</table>
CMS
A: 

Excellent, thank you.

Josh
This is not an answer. You should delete this and post it as a comment.
Peter Ajtai
The add comment button is not available for me on that post, for some reason, though I can comment here. :/ That's also why it isn't approved.
Josh