The worm The worm - 2 months ago 5
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

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 = a.map(function(entry) {
    return "<p>" + entry.replace(/&/g, "&amp;").replace(/</g, "&lt;") + "</p>";
}).join("");

...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");
    p.appendChild(document.createTextNode(entry));
    displayListOfMatches.appendChild(p);
});

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

Comments