Reputation: 37
Here is my sample html.
<table class = "one">
<thead>..</thead>
<tbody>
<tr>
<td>"Element 1<td>
</tr>
</tbody>
</table>
<table class = "one">
<thead>..</thead>
<tbody>
<tr>
<td>"Element 2<td>
<td>"Element 3<td>
</tr>
</tbody>
</table>
I am using cheerio to parse through the tables but unfortunately, I am not able to select a specific table as the tables do not have any ids or belong to different classes. The below code pulls all the rows from both the tables. I had to compare the output with known elements (for example "element2") to fix up an index that I can use to identify tables. But is there any better way using cheerio to pick up the first table on the page or just the second table on the page?
var $ = cheerio.load(sampleHTML);
$('table tr').each(function (i, element) { ..}
Upvotes: 3
Views: 1730
Reputation: 4676
Yes, there are multiple methods:
1) Use a :first-of-type
, :last-of-type
, :nth-of-type(n)
, :first-child
, :last-child
, or nth-child(n)
selector. Some examples:
// to select rows in table 1:
$('table:first-of-type tr')
$('table:nth-child(1) tr')
// to select rows in table 2:
$('table:nth-of-type(2) tr')
$('table:last-child tr')
2) Use the built-in .first()
, .last()
, or .eq(n)
filtering methods (or .filter()
itself). With these, you'd select all table
s, filter down to the table
you want, then find all tr
s in that table.
// to select rows in table 1:
$('table').first().find('tr')
$('table').eq(0).find('tr')
// to select rows in table 2:
$('table').last().find('tr')
$('table').filter(i => i === 1).find('tr')
Upvotes: 4