I'm looping through several instances of HTML that looks like this:
<div class="matchup-container">
<div class="gamequestion">
<strong>NBA: Who will WIN this matchup?</strong>
</div>
<table class="mg-gametableQ">
<tbody>
<tr>
<td class="mg-column1 start">
<div class="matchupDate">
<span class="startTime">11:00 AM</span>
</div>
</td>
<td class="mg-column3 opponents ">
<span>
<strong>
<a>Team</a>: Win
</strong>
</span>
</td>
</tr>
<tr>
<td class="mg-column1 start">
<div class="matchupDate">
<span class="startTime">11:00 AM</span>
</div>
</td>
<td class="mg-column3 opponents ">
<span>
<strong>
<a>Team</a>: Win
</strong>
</span>
</td>
</tr>
</tbody>
</table>
</div>
There are several matchup-container divs to loop through, so I'm using .each() to do that. Then I want to loop through each mg-column3 inside that div, so I use .each() again. Finally, I want to pull the text inside the <a> (in this case, "Team"), and append that inside the mg-column3 div. My jQuery code is here:
$('.matchup-container').each(function() {
var title = $.trim($(this).find('.gamequestion').text());
$(this).find('.mg-column3').each(function () {
if (isStraightUp(title))
{
var teams = getStraightUpTeams(this);
$(this).append('<span class=odds-favorite>' + teams[0] + '</span>');
}
});
});
function isStraightUp (title)
{
return true;
}
function getStraightUpTeams(matchup)
{
var teams = [];
teams[0] = $(matchup).find("a")[0].text();
teams[1] = $(matchup).find("a")[1].text();
return teams;
}
But nothing happens. The Chrome dev tools tell me that I can't call .text() on an undefined element, so everything crashes. But I can't figure out why the jQuery isn't grabbing the text inside the <a> tags that I want. Here's a JSFiddle. Can anyone help?
mg-column3elements only contain a singleaeach. Why are you trying to access 2? The 2nd doesn't exist.