5

I'm trying to loop through an Array which then uses innerHTML to create a new

  • element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
    window.onload = function() {
    
    // Read value from storage, or empty array
    var names = JSON.parse(localStorage.getItem('locname') || "[]");
    var i = 0;
    
        n = (names.length);
        for (i = 0; i <= (n-1); i++) {
            var list = names[i];
            var myList = document.getElementById("list");
            myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
        }
    }
    

    I have a UL with the id 'list' in my HTML.

  • Bart S.
    • 129
    • 2
    • 9

    2 Answers2

    9

    Change your for loop:

    for (i = 0; i <= (n-1); i++) {
        var list = names[i];
        var myList = document.getElementById("list");
        myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
    }
    

    Use += instead of =. Other than that, your code looks fine.

    chris97ong
    • 6,870
    • 7
    • 32
    • 52
    • 1
      Note that `+=` on `.innerHTML` [is not optimal](https://stackoverflow.com/questions/11515383/why-is-element-innerhtml-bad-code). Prefer `myList.insertAdjacentHTML('beforeend', htmlToAppend)` – Ivar Feb 11 '21 at 10:39
    0

    I suggest you to first make a div by create element. there you add your innerHTML and after that you can do the appendchild. That will work perfectly for this type of scenario.

    function displayCountries(countries) {
    const countriesDiv = document.getElementById('countriesDiv');
    countries.forEach(country => {
        console.log(country.borders);
        const div = document.createElement('div');
        div.classList.add('countryStyle');
        div.innerHTML = `
        <h1> Name : ${country.name.official} </h1>
        <h2> Capital : ${country.capital} </h2>
        <h3> Borders : ${country.borders} </h3>
        <img src="${country.flags.png}">
        `;
        countriesDiv.appendChild(div);
    });
    

    }