Search code examples
javascriptjqueryweb-scrapinggreasemonkey

Greasemonkey scraper code grabs letters instead of words?


I'm writing a simple userscript that scrapes some sports data and places it in a table at the top of the page. However, instead of placing each team name in its own row it breaks out each word into individual letters and places them in rows.

Source HTML:

<span class="team-title" id="firstTeamName">Oakland Raiders</span>

Sample Code:

$(document).ready(function () {

$('#navFixed').after('<table id="tbone"></table>'); //navFixed is just an element at the top of the page

var team1 = $('span#firstTeamName').text();

for (var i = 0; i < team1.length; i++) {
    var txt = $('<tr><td></td></tr>').text(team1[i]);
    $('#tbone').append(txt);
    }
});

Sample HTML Output:

<table id="tbone">
    <tr><td>O</td></tr>
    <tr><td>a</td></tr>
    <tr><td>k</td></tr>
    <tr><td>l</td></tr>
    ...
</table>

Ideal Output:

<table id="tbone">
<tr>Oakland Raiders</tr>
</table>

Any thoughts?


Solution

  • .text() returns a string, which is what you want. Looping through a string yields individual letters. Don't do that. ;)

    I suspect that you wanted to loop through the teams. Do that by selecting all the .team-title nodes and looping through them with jQuery's .each().
    See this code:

    $("button").click ( function () {
        //--- Greasemonkey javascript follows...
        var targTble    = $('<table id="tbone"></table>').insertAfter ("#navFixed");
        var teams       = $(".team-title");
    
        teams.each ( function () {
            var teamName = $(this).text ().trim ();  //-- Always beware of whitespace
            targTble.append ('<tr><td>' + teamName + '</td></tr>');
        } );
        //--- End of Greasemonkey javascript.
        this.disabled = true;
    } );
    .team-title {background: #ddd; font-size: 80%;}
    table {border-collapse: collapse;}
    table, td {border: 1px solid green;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <span id="navFixed"></span><br>
    <span class="team-title" id="firstTeamName">Oakland Pirates</span><br>
    <span class="team-title" id="firstTeam_02"> San Fran Gold diggers</span><br>
    <span class="team-title" id="firstTeam_03"> Dallas Cow pokes</span><br>
    <button>Run Greasemonkey code</button>