2

I need a script where I can get the 2D array of the row and columns of the html table inside div.

The expected output is

[
    ["Company", "Contact", "Country"],
    ["Alfreds Futterkiste", "Maria Anders", "Germany"],
    ["Centro comercial Moctezuma", "Francisco Chang", "Mexico"],
    ["Ernst Handel", "Roland Mendel", "Austria"],
    ["Island Trading", "Helen Bennett", "UK"],
    ["Laughing Bacchus Winecellars", "Yoshi Tannamuri", "Canada"],
    ["Magazzini Alimentari Riuniti", "Giovanni Rovelli", "Italy"]
]

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div id="results-table">
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

<script>
prompt("copy this text",$("#results-table table").text())

</script>

I need a script where I can get the 2D array of the row and columns of the html table inside div.

4 Answers 4

4

If you obtain a HTMLTableElement, you can get the rows and then get the cells inside:

const table = document.querySelector("div#results-table > table"), // get the table
  rows = Array.from(table.rows), // get the <tr> elements inside it and convert it to an array
  cells = rows.map(row => Array.from(row.cells).map(cell => cell.textContent)); // gets a 2d list of cells. you could use innerHTML or innerText instead of textContent.
Sign up to request clarification or add additional context in comments.

1 Comment

Good catch, thanks. This is proof that I should always test my code.
2

const trs = document.querySelectorAll('#results-table tr');

const result = [];

for(let tr of trs) {
  let th_td = tr.getElementsByTagName('td');
  if (th_td.length == 0) {
    th_td = tr.getElementsByTagName('th');
  }
  
  let th_td_array = Array.from(th_td); // convert HTMLCollection to an Array
  th_td_array = th_td_array.map(tag => tag.innerText); // get the text of each element
  result.push(th_td_array);
}

console.log(result);
<div id="results-table">
  <table>
    <tr>
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial Moctezuma</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
    </tr>
    <tr>
      <td>Ernst Handel</td>
      <td>Roland Mendel</td>
      <td>Austria</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>Helen Bennett</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Yoshi Tannamuri</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Giovanni Rovelli</td>
      <td>Italy</td>
    </tr>
  </table>

Comments

1

Use a reducer, something like

const toValues = [...document.querySelectorAll(`#results-table tr`)]
  .reduce( (acc, row, i) => 
    acc.concat( [ [...row.querySelectorAll(i < 1 ? `th` : `td`) ]
      .map(c => c.textContent) ] ),
  []);
document.querySelector(`pre`).textContent = JSON.stringify(toValues, null, 2);
.demo {
  display: none;
}
<pre></pre>

<div id="results-table" class="demo">
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

Comments

0

with this HTML,

<div id="results-table">
    <table>
    </table>
</div>

use this script to fill the table:-

var data = [
    ["Company", "Contact", "Country"],
    ["Alfreds Futterkiste", "Maria Anders", "Germany"],
    ["Centro comercial Moctezuma", "Francisco Chang", "Mexico"],
    ["Ernst Handel", "Roland Mendel", "Austria"],
    ["Island Trading", "Helen Bennett", "UK"],
    ["Laughing Bacchus Winecellars", "Yoshi Tannamuri", "Canada"],
    ["Magazzini Alimentari Riuniti", "Giovanni Rovelli", "Italy"]
];

function fillTable(data) {
    data.map((row, i) => {
        let htmlToAdd = '<tr>'
        row.map(cell => {
            if (i === 0) {
                htmlToAdd += '<th>' + cell + '</th>';
            } else {
                htmlToAdd += '<td>' + cell + '</td>';
            }
        });
        htmlToAdd += '</tr>';
        document.querySelector('#results-table table').innerHTML += htmlToAdd;
    })
}

fillTable(data);

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.