Inserting elements into an HTML list

Asked

Viewed 118 times

0

I wish that when sending an element in the input, all elements present in the name array are displayed one below the other after the click, and not all in the same line as is currently happening

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UFT-8">
  <title> </title>
</head>
<body>

    <input type="text" id="nome" value="insira o nome" onfocus="this.value='';"/>
    <button onClick="adicionar()">Adicionar</button>

    <div class="exibir">
        <ul id="lista">
        </ul>
    </div>
    <script>

var nomes = ["Diego", "Gabriel", "Lucas"];

//criar elemento para cada campo
const elemDie = document.createElement('li')
const elemGab = document.createElement('li')
const elemLuc = document.createElement('li')

//cada elemento recebe o seu conteúdo referente ao vetor nomes
elemDie.innerHTML = nomes[0]
elemGab.innerHTML = nomes[1]
elemLuc.innerHTML = nomes[2]


        //adicionar cada elemento na lista
lista.appendChild(elemDie)
lista.appendChild(elemGab)
lista.appendChild(elemLuc)

//função para adicionar mais um nome à lista
        function adicionar(){
            var coleta = document.getElementById("nome")
            nomes.push(nome.value)//inserindo o elemento digitado dentro do array nomes
            var nomeDig = document.createElement('li')
            nomeDig.innerHTML = nomes
            lista.appendChild(nomeDig)

    }
    </script>
</body>
</html>

How can I solve this problem?

1 answer

1

The problem with your code is that by doing nomeDig.innerHTML = nomes vc is inserting the array into Html, rather than just another name. I gave a little improved in your code because it was very plastered as you can see in the example below:

var nomes = ["Diego", "Gabriel", "Lucas"];

for (var i = 0; i < nomes.length; i++) {
  var lis = document.createElement('li');
  lis.innerHTML = nomes[i];
  lista.appendChild(lis);
}

//função para adicionar mais um nome à lista
function adicionar() {
  var coleta = document.getElementById("nome").value;
  var nomeDig = document.createElement('li');

  nomes.push(coleta);
  nomeDig.innerHTML = coleta;
  lista.appendChild(nomeDig);
}
<input type="text" id="nome" value="insira o nome" onfocus="this.value='';" />
<button onClick="adicionar()">Adicionar</button>

<div class="exibir">
  <ul id="lista"></ul>
</div>

Browser other questions tagged

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