Sign in
Log inSign up

How do I correctly populate a ul with new items from an array (JavaScript)

Default profile photo
Anonymous
·Jan 15, 2019

been working on a search history list for my web app and I've been semi-successful. The idea is that a user types a web address into a textarea. The user then clicks a button which saves the address (if valid) to an array called web_history. I then want to show the 10 most recent searches in a dropdown using list items, however the current JS code I have duplicated the array items multiple times, probably because of my forEach loop.

var web_history = [];

function add_to_history() {
    var ul = document.createElement('ul');

    document.getElementById('history_list').appendChild(ul);

    web_history.forEach(function (item) {
        var li = document.createElement('li');
        ul.appendChild(li);

        li.innerHTML += item;

    });

}

This code, when implemented, displays the list like so;

google.com

facebook.com google.com

reddit.com facebook.com google.com.

where in reality i just want it to show this;

google.com facebook.com reddit.com

Is there anyway I can refresh the list so that it doesn't show the original