'cheerio fetch tr:nth-child() length for iteration

All,

I am using cheerio package for web scraping,

cheerio tr selector as below. i want to find length of x to iterate

body > table > tbody > tr:nth-child(x) > th:nth-child(2)

Below is my score card html, i want to calculate the total marks of subjects.

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"/><title>Student Score Card</title><h3>Score card</h3>
<table>
<tr><th>Subject</th><th>Marks</th></tr>
<tr><th>English</th><th>78</th></tr>
<tr><th>Maths</th><th>98</th></tr>
<tr><th>Science</th><th>83</th></tr>
<tr><th>Lab</th><th>80</th></tr>
<tr><th>Physical</th><th>75</th></tr>

</table></html>


here i know the row count as 6, so hard coded the value. however it may change in future. so not able to find the max value via code, looking for help here. Sample logic

const $ = cheerio.load(scorecard.html);
let total = 0;
for(i=0;i<6;i++){
total += parseInt($("body > table > tbody > tr:nth-child("+i+") > th:nth-child(2)").text().valueOf());

}
console.log(total);


Solution 1:[1]

If I understand correctly what you are trying to do, then this should help.

const selectors = Array.from($("body > table > tbody > tr"));
let total = 0;
for (let i = 0; i < selectors.length; i++) {
  total += parseInt($(selectors[i]).find("th:nth-child(2)").text());
}
console.log(total);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1