html - How to set table cell value using jquery -


i set value of cells of table iterating through them. ideally access html table array i.e. $("#tbl")[row][col]="5"

this not work.

$(document).ready(function() {     (var row = 0; row < 3; row++) {         (var col = 0; col < 3; col++) {             $("#tbl").children().children()[row].children()[col].append("sdfasdf");         }     } }); 

this works dont know why!!!

  1. i dont understand $("#tbl").children().children() why need 2nd children
  2. why 3rd children not function i.e. children() 1st 2.
  3. why is'nt innerhtml not function i.e. innerhtml()

    $(document).ready(function() {     (var row = 0; row < 3; row++) {         (var col = 0; col < 3; col++) {             $("#tbl").children().children()[row].children[col].innerhtml = "h!";         }     } }); 

if want iterate on each cell in table, either of following work:

$('#tbl td').each(function () {     var $cell = $(this);     // current <td> });  // or,  $('#tbl tr').each(function () {     var $row = $(this);     $row.children().each(function ()     {         var $cell = $(this);         // current <tr> , <td>     }); }); 

if want access table array, you're going have build array yourself:

var arr = $('#tbl > tbody > tr').map(function () {     return $(this).children().map(function ()     {         return $(this);     }); }); 

however, jquery doesn't expose api such you'll (ever) able simple assignment, in arr[row][col] = 5;. above array, work:

arr[row][col].text(5); 

demo


edit

(1) dont understand $("#tbl").children().children() why need 2nd children

because jquery's .children() function returns set of element's immediate descendants, not descendents (e.g. children + grandchildren + ...).

(2) why 3rd children not function i.e. children() 1st 2.

because when use array notation access elements of jquery collection, underlying dom element, not jquery object. use .eq(i) instead of [i]:

$("#tbl").children().children().eq(row).children().eq(col).append("sdfasdf"); 

(3) why is'nt innerhtml not function i.e. innerhtml()

as in answer question #2, ...children()[col] returns dom element, not jquery object. browsers support dom element.innerhtml property.

when using .eq(i) instead of [i], above, use .html() jquery function.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -