Reputation: 1022
I'm learning jQuery I still have some problems with DOM. I have one table that contains 3 rows and each row have 5 content. I need to add a forth row and its respective contents. Here's my code:
<table>
<tr>
<td>content</td>
<td>content</td>
<td>content</td>
<td>content</td>
</tr>
<table>
Above is the example How the table should be did Below is my jQuery code
var arrayContent = ['Content1','Content2','Content3','Content4','Content5'];
$('table').append(function(){
return $('<tr>').append(function(){
for(var i = 0; i < arrayContent.length; i++){
return $('<td>')
}
})
})
So this code abode only add one tag and I need to add more to my page. Does anyone know how I can improve or suggest new way to do this?
Upvotes: 1
Views: 71
Reputation: 1391
Here's a slightly different approach:
var arrayContent = ['Content1','Content2','Content3','Content4','Content5'];
function foo() {
var dom = '<tr>';
for (var i = 0; i < arrayContent.length; ++i)
dom += '<td>' + arrayContent[i] + '</td>';
dom += '</tr>';
$('table').append(dom);
}
window.onload = foo; // here you can call the function on other events too, e.g. onclick
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
Upvotes: 1
Reputation: 15501
// comments inline
var arrayContent = ['Content1','Content2','Content3','Content4','Content5'];
$('table').append(function(){
return $('<tr>').append(function(){
var td = ''; // create an empty string
for(var i = 0; i < arrayContent.length; i++){
td += '<td>' + arrayContent[i] + '</td>'; // compose the table data
}
return td;
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
Then, in your browser's web inspector, you will get:
Upvotes: 1