3

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) { ..} 
1
  • 1
    Have you tried the nth selector: 'table:nth-child(2) tr' ? This example will select the tr's from the second table. More info: w3schools.com/jquery/sel_nthchild.asp Commented Aug 10, 2017 at 2:37

1 Answer 1

4

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 tables, filter down to the table you want, then find all trs 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')
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Tried the second method of filtering. Worked like a charm. Thanks

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.