How to fill a <li> tag created with Javascript?

Asked

Viewed 104 times

0

I want to fill in the tags li with what you have in the array nomes.

I know what the attribute is for value serves, it is far from what I want to do. But I left there to illustrate.

    var nomes = ["Diego", "Gabriel", "Lucas"];
    var listaUl = document.querySelector('div#app ol.lista'); 

    function listarNomes(nomes) {
        for(let i = 0; i <= nomes.length-1; i++){
            var item = document.createElement('li');
            item.setAttribute('name', nomes[i]); //é aqui que preciso de ajuda
            listaUl.appendChild(item);
        }
    }    
  • 1

    Instead of i <= nomes.length-1, use i < nomes.length.

1 answer

2


I’m not sure I understand the question, but to do what you described setAttribute() would not help, therefore, it serves to set values to Html attributes as the method name itself demonstrates, in your case a textContent would know what you want:

var nomes = ["Diego", "Gabriel", "Lucas"];
var listaUl = document.querySelector('div#app ol.lista');

function listarNomes(nomes) {
  for (let i = 0; i <= nomes.length - 1; i++) {
    var item = document.createElement('li');
    item.textContent = nomes[i];
    listaUl.appendChild(item);
  }
}

listarNomes(nomes)
<div id="app">
  <ol class="lista"></ol>
</div>

Browser other questions tagged

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