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';

const getData = () => {
  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 getData in case data changes.


Solution 2:

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

const getData = () => {
    axios
      .get(" https://pokeapi.co/api/v2/pokemon/charmander")
      .then((response) => {
        const stats = response.data.moves;
        // Create <ul> tag
        const ul = document.createElement('ul');
        stats.forEach((obj) => {
            // Create <li> tag
            const 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 DOM
        document.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?"