I have a table with multiple rows (dynamically) with cell data.
I want to get the each row data and append to as list item
Table
Desired Output:
Raj
- English: 86
- Maths: 73
- Science: 68
Mukund
- English: 45
- Maths: 39
- Science: 64
$('table tr').each( (tr_idx,tr) => {
$(tr).children('td').each( (td_idx, td) => {
$('#results ul').html('<li>' + $(td).text() + '</li>');
});
});
body{font-family:Verdana;font-size:16px}
table, td{
border:1px solid #000000;
border-collapse:collapse;
}
td{
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table-1">
<tr>
<td>Name</td>
<td>English</td>
<td>Maths</td>
<td>Science</td>
</tr>
<tr>
<td>Raj</td>
<td>86</td>
<td>73</td>
<td>68</td>
</tr>
<tr>
<td>Mukund</td>
<td>45</td>
<td>39</td>
<td>64</td>
</tr>
<tr>
<td>Bhairav</td>
<td>85</td>
<td>93</td>
<td>79</td>
</tr>
<tr>
<td>Bhairav</td>
<td>85</td>
<td>93</td>
<td>79</td>
</tr>
</table>
<div id="results">
<h3>
Information
</h3>
<ul>
</ul>
</div>
You need to nest the LIs
NOTE: I wrapped the header in THEAD and the body in TBODY to have valid HTML, which also is easier to parse
I made two versions with some CSS
const $ul = $('#results ul')
const subjects = $('table thead th').map(function() {
return $(this).text()
}).get().slice(1);
$('table tbody tr').each((tr_idx, tr) => {
const [name, ...grades] = $(tr).find('td').map(function() {
return $(this).text();
}).get();
$ul.append(`
<li>
${name}
<ul>
${subjects.map((subject, i) => `<li>${subject}: ${grades[i]}</li>`).join('')}
</ul>
</li>
`);
});
// alternative to align the grades
$('table tbody tr').each((tr_idx, tr) => {
const [name, ...grades] = $(tr).find('td').map(function() {
return $(this).text();
}).get();
$ul.append(`
<li>
${name}
<ul class="grade-list">
${subjects.map((subject, i) => `<li class="grade-item">${subject}: <span>${grades[i]}</span></li>`).join('')}
</ul>
</li>
`);
});
body {
font-family: Verdana;
font-size: 16px
}
table,
td {
border: 1px solid #000000;
border-collapse: collapse;
}
td {
padding: 5px;
}
.grade-list {
list-style-type: none;
/* Remove bullet points */
padding: 0;
}
.grade-item {
display: flex;
justify-content: space-between;
max-width: 200px;
margin: 5px 0;
padding: 2px 5px;
background-color: #f9f9f9;
border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table-1">
<thead>
<tr>
<th>Name</th>
<th>English</th>
<th>Maths</th>
<th>Science</th>
</tr>
</thead>
<tbody>
<tr>
<td>Raj</td>
<td>86</td>
<td>73</td>
<td>68</td>
</tr>
<tr>
<td>Mukund</td>
<td>45</td>
<td>39</td>
<td>64</td>
</tr>
<tr>
<td>Bhairav</td>
<td>85</td>
<td>93</td>
<td>79</td>
</tr>
<tr>
<td>Bhairav</td>
<td>85</td>
<td>93</td>
<td>79</td>
</tr>
</tbody>
</table>
<div id="results">
<h3>
Information
</h3>
<ul>
</ul>
</div>