mrrmatinsi mrrmatinsi -4 years ago 51
HTML Question

Add content to specific columns in table using jQuery

I have a table structure looking something like this. One outer table and in almost each td I got an inner table.

<table class="outertable">
<tr>
<td>
<table class="innertable">
<tr><td></td></tr>
<tr><td></td></tr>
</table>
</td>
<td>
<table class="innertable">
<tr><td></td></tr>
<tr><td></td></tr>
</table>
</td>
</tr>
.....
</table>


With jQuery I need to loop through each td in the outer table to add some unique content in some specific tds. I have been trying to use the following code. It works fine if the outer table doesn't have any child tables but as you can understand it doesn't work with the child tables. So how can I loop through each td in the table to add content?

var row = 0;
car column = 0;
for (var i = 0; i < list.length; i++) {
$(".outertable tr:eq(" + row + ") td:eq(" + column + ")").append(list[i].content);
if (column == 1) {
column = 0;
row++;
} else {
column++;
}
}

Answer Source

I believe your problem is the fact that your CSS selectors are greedy. ".outertable tr" will get all children 'tr' elements under '.outertable'. Instead, adjust the selector to only get direct children ".outertable > tr". Same goes for the 'td' part of the selector. So...

$(".outertable > tr:eq(" + row + ") > td:eq(" + column + ")").append(list[i].content);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download