append function only adds last item of my array

Asked

Viewed 38 times

1

I have the following code. For some reason at the time of giving the append to show my li With my data it only shows the last item of my array. Please someone help me

    window.onload = initPage;
    async function initPage(){
    //pega os dados do banco de dados
        const clients = await GetAll( )
        show(clients)
    }

    function show(data) {
        //cria uma div customizada
        const myDiv = createDiv()
        const idSpan = document.createElement('span')
        const nameLi = document.createElement('li')

        for (let client of data) {
            idSpan.textContent = client.id
            nameLi.textContent = client.firstName
            nameLi.prepend(idSpan)
            nameLi.append(myDiv)
            document.querySelector('#UlList').append(nameLi)
        }

    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="CSS/style.css">
        <title>Clientes</title>
    </head>
    <body>
        <header class="cabecalho">
            <div class="logo">
                <a href="#inicio">
                    <img src="assets/LogoIcone.png" alt="Logo">
                </a>
            </div>
            <nav class="menu">
                <ul>
                    <li>
                        <a href="#inicio">Inicio</a>
                    </li>
                    <li>
                        <a href="#mylist" target="_self">Lista</a>
                    </li>
                    <li>
                        <a href="#Logs">Logs</a>
                    </li>
                </ul>
            </nav>
        </header>
          <div id="wapper">
            <div id="myform">
              <form>
                <h3>Entrar em contato</h3>
                <input type="text" id="firstName" name="firstName" placeholder="First name"/>
                <input type="text" id="lastName" placeholder="Last name"/>
                <input type="text" id="phoneNumber" placeholder="Phone number"/>
                <input type="email" id="email" placeholder="Email"/>
                <input type="password" id="password" placeholder="Sua senha"/>
                <input type="button"  id="Acao" value="Enviar"/>
              </form>
            </div>
            <div id="mylist">
              <h2>List Item Hover Effects</h2>
              <ul id="UlList">
                
              </ul>
            </div>
          </div>
          <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
          <script type="module" src="app.js"></script>
      </body>
    </html>
  • It just prints it shows the last item of my array and ignores the rest

  • 1

    You are using the same instance and overwriting only its value is because of this

1 answer

2


Using the same instance and overwriting only the value, examples:

The wrong way:

const names = ["Autur", "Pamela", "Vanessa"];

function show(values) {
  const ulNames = document.getElementById("ulNames");
  const li = document.createElement("li"); // lugar errado
  names.forEach(function(item){    
    li.innerHTML = item;
    ulNames.append(li);
  });
}

show(names);
<ul id="ulNames">
</ul>

The right way:

const names = ["Autur", "Pamela", "Vanessa"];

function show(values) {
  const ulNames = document.getElementById("ulNames");  
  names.forEach(function(item){    
    //sempre nova instância
    const li = document.createElement("li"); // lugar certo
    li.innerHTML = item;
    ulNames.append(li);
  });
}

show(names);
<ul id="ulNames">
</ul>

What is the difference from the wrong way to the right: in the right form in each passage within the forEach a new instance of the element is created and when it is added to tag ul is a new item, in the wrong form is the same instance and with that only its value is overwritten in the instance that is outside the forEach.


In your code it’s something like this to fix:

function show(data) {
    /cria uma div customizada           
    for (let client of data) {
        const myDiv = createDiv();
        //lugar certo porque são novos itens (novas instâncias)
        //não sobrescrevendo a já criada anteriormente.
        const idSpan = document.createElement('span')
        const nameLi = document.createElement('li')
        idSpan.textContent = client.id
        nameLi.textContent = client.firstName
        nameLi.prepend(idSpan)
        nameLi.append(myDiv)
        document.querySelector('#UlList').append(nameLi)
    }
}
  • Thanks novic got it... but just to complement the function createDiv() should stay within the for-of block otherwise happened the same as was happening with the li. But the code worked Thank you...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.