javascript – How to scan an array and insert the elements in HTML with JS

Question:

I'm studying the JS DOM and I had some difficulties. I need to show the elements of this vector as HTML li tags: let nomes = ["Diego", "Gabriel", "Lucas"]; My code is this:

 function gerar(){ let nomes = ["Diego", "Gabriel", "Lucas"]; let lista = document.querySelector('#lista'); let item = document.createElement('li'); for(let item of nomes){ lista.appendChild(item); } }
 <input type="button" onclick="gerar()" value="Clique"> <ul id="lista"> </ul> <script src="index.js"></script>

I need the vector to become an unordered list, but the code doesn't work. Does anyone know how to do it?

Answer:

There are other different ways to create DOM elements, approaching your example you can create as follows:

function gerar(){
    let nomes = ["Diego", "Gabriel", "Lucas"];
    let lista = document.getElementById('lista');
    for(var i = 0; i < nomes.length; i++){
        let item = document.createElement('li');
        item.appendChild(document.createTextNode(nomes[i]));
        lista.appendChild(item);
    }
}
<ul id="lista"></ul>
<input type="button" onclick="gerar()" value="Clique">

Example in JSFiddle

Scroll to Top