Does Firefox browser not recognize table.cells?

匆匆过客 提交于 2019-12-01 08:48:20

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/10701076/does-firefox-browser-not-recognize-table-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!