Search code examples
javascripthtmlarraysinnerhtml

Random commas appearing on html page on inspect when not in code


I have a simple HTML page and I am mapping an array to populate a div with cards. The card alignment was all wrong, so when I inspected it, I saw that there are commas after every card except the last one, which is ruining the alignment. I haven't added these commas in the code. My code:

    itemsdiv.innerHTML = items.map(el => {
        return (`
        <div class="item">
            <span class="item-title">${el.name}</span>
            <img class="item-image" src=${el.src}>
            <div class="item-details">
                <span class="item-color">${el.color}</span>
            </div>
        </div>
        ` )
    })

itemsdiv is an empty div to populate, and items is an array that looks like this:

    items = [
        {
            name: 'T-Shirt',
            src: 'Images/Shirt.png',
            color: 'blue',
        },
        {
            name: 'Coffee Cup',
            src: 'Images/Coffee.jpg',
            color: 'red',
        }
    ]

When I inspect it looks something like this:

<div class="itemsdiv">
   <div class="item"></div>
   ","
   <div class="item"></div>
   ","
   <div class="item"></div> 
</div>

Solution

  • After .map try tagging on .join(" ")

    Solution based on @VLAZ's comment:

    When you convert an array to a string, it automatically joins the elements with commas between them. Assigning an array to innerHTML converts it to a string.