When logging `.map()` to the console, it gives me a rough idea of what I want. However, adding the same line of code via innerHTML only displays

After browsing Stack Overflow for some time, I finally created an account and am now asking my first question.

I recently began working with APIs to enhance my web development skills. I started by creating an anime information app that I enjoyed, and then moved on to another project focusing on NHL teams and rosters using an API from here.

The team info and logos section of my project is functioning well, but I am facing challenges when trying to retrieve the roster for each team. Although using .map() in my function displays the desired output in the console, adding the same code to .innerHTML only shows the last player's name instead of the entire roster. I have attempted for loops and promise chaining without success.

If anyone could provide guidance or point me in the right direction, I would greatly appreciate it.

 function getRosterByID(teamID){
  fetch(`https://statsapi.web.nhl.com/api/v1/teams/${teamID}/roster`)
  .then(res => res.json())
  .then(data => {
    data.roster.map(players => {
      console.log(players.person.fullName);
      roster.innerHTML = `
      <div>
        <dl>
          <dt>${players.person.fullName}</dt>
        </dl>
      </div>`;
    }).join();
    roster.style.display = 'flex';
  });
}

Answer №1

When utilizing innerHTML, it does not append to the existing content but replaces it entirely. It is recommended not to use map() as a loop; instead, forEach should be used for that purpose.

However, by employing map, you can retrieve all the text present.

 function fetchPlayerNamesByTeamID(teamID){
  fetch(`https://statsapi.web.nhl.com/api/v1/teams/${teamID}/roster`)
  .then(response => response.json())
  .then(data => {
    const playerList = data.roster.map(player => {
      console.log(player.person.fullName); // Outputting player name to console
      return  `
      <div>
        <dl>
          <dt>${player.person.fullName}</dt>
        </dl>
      </div>`;
    }).join('');
    renderPlayers.innerHTML = playerList; // Displaying player names on the webpage
    renderPlayers.style.display = 'flex'; // Setting display style to flex
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Formatting issue with chords and lyrics

I am in the process of creating a website that features chords and lyrics. However, I want to ensure that the chords cannot be copied due to some formatting issues. The main objective is for users to be able to copy the chord and lyrics together and paste ...

Repetitive bouncing in a trampoline leads to the error message "Call stack has reached maximum size"

I have been delving into the world of blockchain and experimenting with a simple implementation of "proof of work". Proof of work: export function mineBlock(difficulty: number, block) { const prefix = Array(difficulty + 1).join("0"); function mine(b ...

Discovering the process of previewing a video upload using react-player

Currently, I have an input that allows users to upload video files of type File. In my application, there is also a react-player component that requires a URL prop, which can be either an array or MediaStream according to its documentation. After doing som ...

Ways to extract individual values from a Json Array and utilize them individually

I have a JSON data structure that I need to parse and separate each field into different arrays, so that I can use them individually. For instance, I want to split my data into two rooms: room 1 and room 2. After separating the data, I need to format it a ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

What is the best method to save a c# object containing arrays in a database?

I am in the process of developing a software using C# and I need to find a way to store data in a database. The challenge I am facing is determining the best approach to store the data of an object that contains two arrays, each with objects that have simi ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

Is there a way to invert my array by utilizing just a single array instead of resorting to using two arrays

While I am still learning JavaScript and programming as a whole, I decided to test out some code for reversing an array using push and pop methods. Even though I am aware that I could easily utilize Array.prototype.reverse(), I wanted to have some fun expe ...

What is the best way to open a page in a new tab within the row command event of a gridview?

Here is the code snippet I am working with: protected void gv_inbox_RowCommand(object sender, GridViewCommandEventArgs e) { int index = Convert.ToInt32(e.CommandArgument); if (e.CommandName == "sign") { Session["TransYear"] = int.Pars ...

Bootstrap4: combining card header and navigation into a single row

How can we use Bootstrap 4 to position navigation and text within a Card Header in order to have them display on a single row? <div class="card"> <div class="card-header"> Heading <ul class="nav nav-pills card-header-pills"> ...

Issue arises when attempting to recursively print a two-dimensional array

When I try to print a 2d array recursively, the method ends up repeating the second column twice with three extra spaces. What can I do to fix this issue? Here is the full code: public static void main(String [] args) { final int ROWS = 2, COLS = 2; ...

How can the top height of a jquery dialog be reduced?

Just starting out with jquery, I've got a dialog box and I'm looking to decrease the height of this red image: https://i.sstatic.net/BuyQL.png Is there a way to do it? I've already made changes in the jquery-ui.css code, like so: .ui-dia ...

What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "ca ...

Creating a typewriter effect with Vue Js

Hey there, I'm having some trouble with the code below while working on my Vue project. It seems to be functioning correctly, but for some reason it's not working in my Vue environment. const text = document.getElementById("text"); const phrase ...

Place the text (menu) adjacent to the navigation bar

I am currently using bootsrap 4 alpha 6 in combination with midnight.js to alter the color of my navigation menu toggler. I am trying to incorporate a text element (MENU) alongside it, similar to the example shown in the Capture image. For the text toggler ...

ES6 module import import does not work with Connect-flash

Seeking assistance with setting up connect-flash for my nodejs express app. My goal is to display a flashed message when users visit specific pages. Utilizing ES6 package module type in this project, my code snippet is as follows. No errors are logged in t ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

Reassigning the memory of a string array in C and creating new strings

Can anyone help diagnose the issue in this code? I'm trying to resize an array of char** and then allocate memory for new strings (char*). void resizeArray(char*** array, int* p_capacity) { int index; int previousCapacity; char **temporar ...

Using Angular to populate textboxes with SQL data

I am encountering an issue with a mat-table that retrieves its data from a database. One of the columns needs to be editable by the user so that they can update the content and reflect changes in the database. The problem lies in loading the data into the ...

Creating a jsp page content with jquery and retrieving request parameters

I am facing an issue with my JSP page where I need to pass the value of request.getParameter("cfgname") to another content page so that it loads correctly. Currently, the code is displaying null instead of the parameter. This is the main JSP page with par ...