If you just want to iterate over each cell in the table, one of the following actions will be performed:
$('#tbl td').each(function () { var $cell = $(this); // do something with the current <td> }); // or, $('#tbl tr').each(function () { var $row = $(this); $row.children().each(function () { var $cell = $(this); // do something with the current <tr> and <td> }); });
If you want to access the table as an array, you have to build the array yourself:
var arr = $('#tbl > tbody > tr').map(function () { return $(this).children().map(function () { return $(this); }); });
However, jQuery does not provide an API so that you (ever) can perform a simple assignment, as in arr[row][col] = 5;
. With the array above, this will work:
arr[row][col].text(5);
Demo
Edit
(1) I do not understand $ ("# tbl"). children (). children () why for a 2nd child is required
Since the jQuery .children()
function returns only a set of elements of immediate descendants, and not all descendants (for example, children + grandchildren + ...).
(2) Why the 3rd child is not a function, i.e. children (), as the 1st 2.
Because when using array notation to access jQuery collection items, you are returning the underlying DOM element, not the jQuery object. Use .eq(i)
instead of [i]
:
$("#tbl").children().children().eq(row).children().eq(col).append("sdfasdf");
(3) Why is'nt innerHTML is not a function, i.e. innerHTML ()
As in the answer to your question # 2, ...children()[col]
returns a DOM element, not a jQuery object. Most browsers support the DOM property of element.innerHTML
.
When using .eq(i)
instead of [i]
as described above, use the .html()
jQuery function.