Reputation: 271
I have a table consisting of multiple rows. Each row contains 5 data cells and the innerHTML of each cell is different:
HTML
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
<td>Data 4</td>
<td>Data 5</td>
</tr>
<tr>
<td>Data 6</td>
<td>Data 7</td>
<td>Data 8</td>
<td>Data 9</td>
<td>Data 10</td>
</tr>
...
JavaScript
The below code gets the data from the first 5 cells, but I need to loop through all rows and then each cell within each row.
var allTableData = [];
var tableData = $('td');
_.each(tableData, (data, i) => {
if (i < 5) {
allTableData.push(data.innerHTML);
}
});
My desired output is:
values: [
['Data 1', 'Data 2', 'Data 3', 'Data 4', 'Data 5'],
['Data 6', 'Data 7', 'Data 8', 'Data 9', 'Data 10'],
[...]
];
How would I get my desired output with JavaScript/JQuery?
Upvotes: 0
Views: 704
Reputation: 56773
You need to iterate over the tr
s, and inside that loop, iterate over the td
s.
var allTableData = [];
var rowData = [];
var tableRows = $('#myTable tr');
var row;
tableRows.each(function() {
rowCells = $(this).find('td');
rowCells.each(function() {
rowData.push($(this).text());
});
allTableData.push(_.clone(rowData));
rowData.length = 0;
});
console.log(allTableData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
<td>Data 4</td>
<td>Data 5</td>
</tr>
<tr>
<td>Data 6</td>
<td>Data 7</td>
<td>Data 8</td>
<td>Data 9</td>
<td>Data 10</td>
</tr>
</table>
https://jsfiddle.net/Lzekdy23/2/
Upvotes: 0
Reputation: 27022
I would do two levels of .map()
:
var arr = $('table tr').get().map(function(tr) {
return $('td', tr).get().map(function(td) {
return $(td).html();
});
});
https://jsfiddle.net/gbgjhj83/
Upvotes: 5