0

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?

1
  • You will need nested loops. The first loop loops through all the <tr> tags and then a loop inside of that loop loops through all the <td> tags. Commented Nov 2, 2016 at 18:25

2 Answers 2

5

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/

Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I needed! Thanks!!
0

You need to iterate over the trs, and inside that loop, iterate over the tds.

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.