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.

    2 Answers 2

    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.

    Sign up to request clarification or add additional context in comments.

    1 Comment

    Note that += on .innerHTML is not optimal. Prefer myList.insertAdjacentHTML('beforeend', htmlToAppend)
    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);
    });
    

    }

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.