0

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

3
  • displayListOfMatches.innerHTML += "<p>" + a[i] + "</p>"; Commented Sep 29, 2016 at 15:20
  • 1
    @ChrisG: Using += with innerHTML is a bad idea. Commented Sep 29, 2016 at 15:21
  • displayListOfMatches.innerHTML = a.join("<br>"); would be one way; no loop Commented Sep 29, 2016 at 15:46

1 Answer 1

1

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.

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

2 Comments

ok yeh think this makes sense. no idea why im getting a syntax error. i have just placed your code inside a function and now it is complaining about the last bracket...
@Theworm: That would be because I left off the ); that should have been at the end of the second code block. :-) Sorry about that. It's there now.

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.