admin管理员组

文章数量:1334386

I have the following JavaScript code.


var myCellCollection = document.getElementById('myTbl').cells;

This works well in IE and it returns a collection of table cells. But the same line returns "undefined" in Firefox. I am using IE 9 and Firefox 12.

I have the following JavaScript code.


var myCellCollection = document.getElementById('myTbl').cells;

This works well in IE and it returns a collection of table cells. But the same line returns "undefined" in Firefox. I am using IE 9 and Firefox 12.

Share Improve this question edited May 18, 2017 at 13:21 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 22, 2012 at 11:24 HorizonHorizon 2914 silver badges14 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You should use document.getElementById("myTbl").getElementsByTagName('td');

Stumbled into this today whilst porting an older Internet Explorer app.

Warning:
container.getElementsByTagName('tagname') returns ALL the elements inside container that matches the query tagname.

Thus table.getElementsByTagName('td') will return all td's including those of nested tables!
However table.cells doesn't do that (where implemented).

Also, obviously, it won't match th. So those cells are not in returned collection, optionally leading to the 'problem' of how to resolve their order relative to the td's...

To shim the expected functionality of table.cells (returning both th and td in DOM-order), I wrote the following simple function:

function tableCells(t){
   if(t.cells) return t.cells; // use internal routine when supported
   for(var a=[], r=t.rows, y=0, c, x; t=r[y++];){
      for(c=t.cells, x=0; t=c[x++]; a.push(t));
   } 
   return a;
}

Alternatively, using 'single return' by 'if-else' packs to the same size exactly, yet the above gzips smaller. PS: I tried concat-ting the table.rows[X].cells, but that didn't work (although I wouldn't feel safe doing so anyways)

Usage example:
var identifier = tableCells( /*reference to table (or thead/tbody/tfoot) here*/ );
It will return an array (not a live collection) like the result from table.cells.

Hope this helps someone

本文标签: javascriptDoes Firefox browser not recognize tablecellsStack Overflow