Reputation: 43
I'm trying to create a dynamic table with jQuery. So far I have this code below:
$(document).ready(function(){
var i=0;
while(i<10){
$('table').append('<tr></tr>');
$('tr').append('<td></td>');
i++;
};
});
It gives me a rather strange result : I get a table as expected, but the first row has 10 columns, the second row has 9 columns and so on...
I was surprised by the result, I was expecting 10 rows with one column.
Upvotes: 2
Views: 51
Reputation: 5681
You need to hold the handle to append the elements to same element.
$(document).ready(function(){
var i=0;
var rowTemplate = '<tr></tr>';
var $table = $('table');
while(i<10){
var $row = $(rowTemplate);
$row.appendTo($table);
$row.append('<td> cell '+i+'</td>');
i++;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
Upvotes: 0
Reputation: 224904
$('tr').append('<td></td>');
This selects every <tr>
in the entire document (including the ones you’ve added in previous iterations) and adds a <td>
to each one. The smallest fix is probably to insert both at once:
$(document).ready(function () {
var i = 0;
while (i < 10) {
$('table').append('<tr><td></td></tr>');
i++;
}
});
Upvotes: 2
Reputation: 3463
First you need to select the table and hold it in a variable
var table = $('table');
in the while loop, you create a new tr
element
var tr = $('<tr></tr>');
append it to the table
table.append(tr);
then you append a new td
element
tr.append('<td></td>')
Upvotes: 3