最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chrome querySelector() of a table into an array - Stack Overflow

programmeradmin3浏览0评论

Using the chrome dev tools and console, I want to create an organised table or array from the HTML table in the console. What I have so far returns a long string of all the span elements:

$('tbody > tr > td > span').text();

Would someone be able to educate me as to how I can create an array of each row in the HTML table?

(site for ref: /?free=true&query= as you can see there's no class's or id's on any of the elements in the table)

EDIT: table structure as requested in ments

<tr>
<td><span data-uname="lotsearchLotnumber">1997</span>
<td><span data-uname="lotsearchLotnumber">FORD</span>
<td><span data-uname="lotsearchLotnumber">45</span>
</tr>
<tr>
<td><span data-uname="lotsearchLotnumber">1998</span>
<td><span data-uname="lotsearchLotnumber">FORD</span>
<td><span data-uname="lotsearchLotnumber">40</span>
</tr>
...

I'd like to output an array like so:

[1997, FORD, 45]
[1998, FORD, 40]
...

Using the chrome dev tools and console, I want to create an organised table or array from the HTML table in the console. What I have so far returns a long string of all the span elements:

$('tbody > tr > td > span').text();

Would someone be able to educate me as to how I can create an array of each row in the HTML table?

(site for ref: https://www.copart./lotSearchResults/?free=true&query= as you can see there's no class's or id's on any of the elements in the table)

EDIT: table structure as requested in ments

<tr>
<td><span data-uname="lotsearchLotnumber">1997</span>
<td><span data-uname="lotsearchLotnumber">FORD</span>
<td><span data-uname="lotsearchLotnumber">45</span>
</tr>
<tr>
<td><span data-uname="lotsearchLotnumber">1998</span>
<td><span data-uname="lotsearchLotnumber">FORD</span>
<td><span data-uname="lotsearchLotnumber">40</span>
</tr>
...

I'd like to output an array like so:

[1997, FORD, 45]
[1998, FORD, 40]
...
Share Improve this question edited May 7, 2019 at 23:59 John107 asked May 7, 2019 at 23:29 John107John107 2,2875 gold badges22 silver badges39 bronze badges 4
  • Your question is pretty vague. What does the original HTML table look like? (show a concise example in the question, don't just link to a different page) What do you want the resulting data structure to look like? What exactly are you trying to acplish? "How [can I] create an array of each row in the HTML table?" $$('tbody > tr') would be a good start but without more details, I'm not sure where you'd go from there. – p.s.w.g Commented May 7, 2019 at 23:51
  • It's not really that vague... the structure is pretty simple, table rows with table cells, I would like to print the value of each row in an array. I'll update my question if it helps. – John107 Commented May 7, 2019 at 23:56
  • Possible duplicate of Convert html table to array in javascript. – antisilent Commented May 7, 2019 at 23:58
  • looks like a jquery question – Mulan Commented May 8, 2019 at 0:01
Add a ment  | 

4 Answers 4

Reset to default 2

Looking at the site, you're going to have to explain a little more what you expect the output to look like. You've got images, some buttons, ratings and standard text to work with, so you'll need some additional logic to sniff that stuff out.

But, generally speaking, this is a good starting point on how to take a given HTML Table and convert it into an array of objects. The assumption in this example is that your table includes the thead and tbody format. If it doesn't, that can be removed from the code.

In addition, I would also point out that if you're just trying to download some data and don't really need a 'permanent solution', you should look into web scrapers such as this

const htmlToArray = (tableElement) => {
  const thead = tableElement.querySelector('thead');
  const tbody = tableElement.querySelector('tbody');
  // Assumes there's only one header row
  const columns = thead.querySelectorAll('tr th');
  const columnNames = [];
  columns.forEach( c => columnNames.push(c.innerText));
  const result = [];
  const bodyRows = tbody.querySelectorAll('tr');
  bodyRows.forEach( r => {
    const tds = r.querySelectorAll('td');
    const obj = {};
    tds.forEach( (td, idx) => {
      obj[columnNames[idx]] = td.innerText;
    });
    result.push(obj);
  });
  return result;
};

const table = document.querySelector('table');
console.log(htmlToArray(table));
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data1</td>
      <td>Data2</td>
      <td>Data3</td>
    </tr>
    <tr>
      <td>Data4</td>
      <td>Data5</td>
      <td>Data6</td>
    </tr>
    <tr>
      <td>Data7</td>
      <td>Data8</td>
      <td>Data9</td>
    </tr>
  </tbody>
</table>

The table itself has an id you can use.

var rows = document.querySelectorAll('#serverSideDataTable tbody tr')

This will find all <tr> elements (table rows) that are inside a <tbody> element (skips the <thead> which contains column names), which in turn must be inside of an element with id 'serverSideDataTable'.

Not sure what you want to do with the rows after that.

CTS_AE shows a great functional approach. Here's another functional solution using Array.from -

const table =
  Array.from(document.querySelectorAll('tr'), tr =>
    Array.from(tr.querySelectorAll('td'), td =>
      td.textContent
    )
  )

console.log(table)
<table>
<tr>
<td><span data-uname="lotsearchLotnumber">1997</span>
<td><span data-uname="lotsearchLotnumber">FORD</span>
<td><span data-uname="lotsearchLotnumber">45</span>
</tr>
<tr>
<td><span data-uname="lotsearchLotnumber">1998</span>
<td><span data-uname="lotsearchLotnumber">FORD</span>
<td><span data-uname="lotsearchLotnumber">40</span>
</tr>
</table>

For contrast, here's an imperative-style answer -

const table = []

for (const tr of document.querySelectorAll('tr')) {
  const row = []
  for (const td of tr.querySelectorAll('td')) {
    row.push(td.textContent)
  } 
  table.push(row)
}

console.log(table)
<table>
<tr>
<td><span data-uname="lotsearchLotnumber">1997</span>
<td><span data-uname="lotsearchLotnumber">FORD</span>
<td><span data-uname="lotsearchLotnumber">45</span>
</tr>
<tr>
<td><span data-uname="lotsearchLotnumber">1998</span>
<td><span data-uname="lotsearchLotnumber">FORD</span>
<td><span data-uname="lotsearchLotnumber">40</span>
</tr>
</table>

There's a lot of magic going on here.

I'm converting the querySelectorAll to an array using a spread.

I'm doing this because querySelectorAll returns a NodeList which is not currently iterable with map; some transpilers/plugins may allow this though.

Then I map the values that I want on up and out.

var trs = [...document.querySelectorAll('tr')];

var data = trs.map(tr => {
  var tds = [...tr.querySelectorAll('td')];
  return tds.map(td => td.innerText);
});

console.log(data);
console.table(data);
<table>
  <tr>
    <td>1997</td>
    <td>FORD</td>
    <td>45</td>
  </tr>
  <tr>
    <td>1998</td>
    <td>FORD</td>
    <td>40</td>
  </tr>
</table>

Protip: If you're looking to see the values more clearly in the console you can use the console.table to see it as a table as shown in the screenshot attached below.

发布评论

评论列表(0)

  1. 暂无评论