The worm The worm - 1 year ago 121
Javascript Question

Display JavaScript array in vertical list

I have an array I have generated and I want to display it in html as a vertical list, preferably as each individual element.

I have done this:

var a = _.intersection(viewedUserLikedUsersArray, loggedInLikedUsersArray);
for (var i=0; i < a.length; i++){
displayListOfMatches.innerHTML = a[i];

but obviously this way will replace the innerHTML with the last element in the array rather than stacking each one on top of each other

Answer Source

You'll probably get people saying to do this:

displayListOfMatches.innerHTML = "<p>" + a.join("</p><p>") + "</p>";

...which works but note that the content of the array entries will be parsed as HTML.

If that's not okay, you can either build an HTML string by replacing those characters via map:

displayListOfMatches.innerHTML = {
    return "<p>" + entry.replace(/&/g, "&amp;").replace(/</g, "&lt;") + "</p>";

...or build the elements as you go, perhaps with forEach:

displayListOfMatches.innerHTML = ""; // You can leave this out if it's empty
a.forEach(function(entry) {
    var p = document.createElement("p");

Of course, in all cases, you can adjust it to use different elements/markup.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download