Skip to content
Advertisement

How to display the contents of an array as a list?

I’d like to output the contents of an array as a list:

value

value

value

However, it’s currently outputting the array like this:

value,value,value

What can I change to display the array contents as a vertical list?

For context, this is displaying an array that updates by adding/removing items based on connections/disconnections to a server. So, when a user connects, their name is added to the array, when they disconnect, the array is wiped and all connected clients send their username back to the array, updating it. The below code simply displays these changes.

HTML:

<section class="membersList">
  <div class="dispUser"></div>
</section>

CSS:

.membersList {
    text-align: center;
    padding: 10px;
    margin-bottom: 10px;
    margin-right: 10px;
    background: #ACD8F0;
    width: 150px;
    border: 1px solid #000000;
    overflow: auto;
    float: right;
}

JavaScript:

socket.on('theitems', function (data) {
      $('.dispUser').html('<p>' + data + '</p>');
      console.log(data);
    });

If I replace .html with .append, it will display it as a list, but will show the changes of the array as they happen, rather than replacing it as a whole, which is what I want.

Advertisement

Answer

The issue with your code is that you’re trying to directly print an array, which gets converted to a string and so you get the result you’re seeing.

You can get the result you want by iterating over the array and inserting a paragraph for each item in it. Here is an example:

const data = [5,6,7,8,9];
const list  = document.getElementById('list');
 
window.onload = () => {
  list.innerHTML = data.map(i => `<li>${i}</li>`).join('');
};
 
<ul id="list"></ul>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement