Reputation: 125
I have a loop that iterates thru all rows in a table. Once I am inside of the table i want to get nested values. For example, wins, losses. That would have the html attribute of [data-stat=wins]
.
This is my code,
const result = await request.get("https://www.basketball-reference.com/boxscores/");
const $ = cheerio.load(result);
var teams = [];
var wins = [];
var losses = [];
$('#confs_standings_E > tbody > tr').each((index, element) => {
var wins = $(element > $('[data-stat=wins]'));
console.log(wins)
console.log($(element).text())
})
Console.log(wins) returns an empty string. But the line after it returns all rows. This seems pretty simple I've just never used JQuery before so not sure how to do this.
Upvotes: 0
Views: 50
Reputation: 14570
You will need to use push()
to add data in your wins
empty array like this below.
You also need to check on whats coming in element
- console.log(element)
and see if data data-stat=wins
is coming is returned at all.
Once its returning something. Then you the code below to push data in your wins = []
array
const result = await request.get("https://www.basketball-reference.com/boxscores/");
const $ = cheerio.load(result);
var teams = [];
var wins = [];
var losses = [];
$('#confs_standings_E > tbody > tr').each((index, element) => {
var wins.push($(element > $('[data-stat=wins]')))
console.log($(element).text())
console.log(wins)
})
Upvotes: 1
Reputation:
I guess you want this if it's only direct children, implied by your inclusion of >
.
$(element).children('[data-stat=wins]'));
Or use .find()
for all descendants.
What you're basically doing is applying the >
greater than operator to an element, comparing to see if it's greater than the jQuery object returned by $('[data-stat=wins]')
. It's valid but not useful.
You're then passing that result to the jQuery function. None of that will produce any kind of desirable result.
Your outer wins
array is unnecessary, unless you were hoping to maintain an external list of values. More likely you just want to use the values you find in the handler.
Upvotes: 0