Skip to content Skip to sidebar Skip to footer

How To Display A List Of Element In As A List In Html From A Javascript Array From An Api?

My JS code is this but I want to be able to get the moves array to be displayed in HTML in a list format, how can I go about doing so? const getData = () => { axios .get('

Solution 1:

You can use a safe helper to populate a node in the page, let's say <div id="list"></div>, so that your code can do something like:

import {render, html} from'//unpkg.com/uhtml?module';

constgetData = () => {
  axios
    .get(" https://pokeapi.co/api/v2/pokemon/charmander")
    .then((response) => {
      const stats = response.data.moves;
      render(document.getElementById('list'), html`<ul>${stats.map((obj) => html`<li>${obj.move.name}</li>`)}</ul>
      `);
    })
    .catch((error) =>console.log(error));
};

That will also do the right thing next time you call getDatain case data changes.

Solution 2:

Here is a proposition requiring no library (VanillaJS only) :

constgetData = () => {
    axios
      .get(" https://pokeapi.co/api/v2/pokemon/charmander")
      .then((response) => {
        const stats = response.data.moves;
        // Create <ul> tagconst ul = document.createElement('ul');
        stats.forEach((obj) => {
            // Create <li> tagconst li = document.createElement('li');
            // Add text to <li>
            li.textContent = obj.move.name;
            // Append <li> to <ul>
            ul.appendChild(li);
        });

        // Append <ul> somewhere in your DOMdocument.getElementById('ul_parent').appendChild('ul');

      })
      .catch((error) =>console.log(error));
};

Post a Comment for "How To Display A List Of Element In As A List In Html From A Javascript Array From An Api?"