Home > Net >  How can I append json data from ajax response to more than one class
How can I append json data from ajax response to more than one class

Time:06-04

I'm brushing up on my jquery and I've run into a roadblock. I'm returning some json data from a fantasy football api and I'm trying to figure out how to map over the data and assign each team owner and name to its own div. My question is essentially this: how can I assign the first member of returned array to the class "player1", the second member of the array to the class "player2" and so on. All I've been able to do is map over the array and display all of the data in one div, but I can't figure out how to assign each array member its own div.

Here's the map function I've been utilizing:

$(document).ready(function() {
    $.ajax({
            url: 'https://api.sleeper.app/v1/league/784456593403224064/users',
            type: 'GET',
            success: function(result) {
                playerData = result.map(result => result.display_name);
                console.log(playerData);
                $("#player1").append(JSON.stringify(playerData));
                // playerData = result
                // console.log(playerData)
            },
            error: function(err) {
                console.log(err)
            }
    })
})

Obviously this appends all of the data to the "player1" class, I just need to figure out how to assign the data like I mentioned above. Thanks in advance!

CodePudding user response:

In your question, you mention classes, but the jQuery selector you're using, #, is for IDs. The class selector uses a .

In any case, you could iterate over the data returned by the API, and use the index of the loop to dynamically build your selector:

playerData.forEach((player, item) => {
    $(`#player${item}`).append(player);
});

Example using your code:

$(document).ready(function() {
    $.ajax({
            url: 'https://api.sleeper.app/v1/league/784456593403224064/users',
            type: 'GET',
            success: function(result) {
                playerData = result.map(result => result.display_name);
                playerData.forEach((player, item) => {
                    $(`#player${item}`).append(player);
                });
            },
            error: function(err) {
                console.log(err)
            }
    })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="player1"></div>
<div id="player2"></div>
<div id="player3"></div>
<div id="player4"></div>
<div id="player5"></div>
<div id="player6"></div>
<div id="player7"></div>
<div id="player8"></div>
<div id="player9"></div>

  • Related