I have a table whose tr needs to be repeat by rendering the value inside td. The values of td comes from get api call using foreach loop. I have already tried to render but my tbody is not coming inside the table. I want it to create using only javascript, no jquery.Here is the code below
var container = document.getElementById("container");
var url = "http://dummy.restapiexample.com/api/v1/employees";
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
container.innerHTML = '<div class="container"><h2>Basic Table</h2><p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p><table class="table"><thead><tr><th>ID</th><th>Firstname</th></tr></thead>'
data.data.forEach(function(count) {
console.log(count);
container.innerHTML += '<tbody><tr><td>' + count.id + '</td><td>' + count.employee_name + '</td></tr></tbody>';
})
}).catch(function() {
console.log("Booo");
});
container.innerHTML = '</table></div>'
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div id="container">
<h2>Basic Table</h2>
<p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p>
</div>
<tbody>elements; you're adding one for each row of data. Also, how to create a table from an array is asked all the time on this website, you should easily find tons of existing answers showing better practice than composing HTML strings.