The worm
The worm

Reputation: 5888

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

Upvotes: 0

Views: 2274

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074238

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.

Upvotes: 1

Related Questions