Dynamically add DIV element with varying values

I would like to create a div card dynamically with varying values depending on the result of my API. Currently, values keep overriding each other because they all share the same element ID. Is there a way for me to dynamically add all the values into their own cards?

res.forEach(x => {
    const div = document.createElement("div");
    div.className = "card mb-4 box-shadow";
    div.innerHTML = `
        <div class="card-header">
           <h4 id="serverName" class="my-0 font-weight-normal"></h4>
        </div>
        <div class="card-body">
           <h1 id="serverPrice" class="card-title pricing-card-title"></h1>
           <p id="serverTraits" class="list-unstyled mt-3 mb-4"></p>
        </div>`

        document.getElementById("content").appendChild(div);
        document.getElementById("serverName").innerHTML = x.name
        document.getElementById("serverPrice").innerHTML = x.price + '$'
        document.getElementById("serverTraits").innerHTML = x.traits
})

Answer

A simple way that works with your current solution is to simply append the index or a number behind your ids

e.g

<!-- your html code becomes something like this -->
<h4 id="serverName1" class="my-0 font-weight-normal"></h4>
<h4 id="serverName2" class="my-0 font-weight-normal"></h4>
<h4 id="serverName3" class="my-0 font-weight-normal"></h4>

When retrieving, likewise, append the index

document.getElementById("serverName" + index).innerHTML = x.name

This way, all your ids will be unique.

EDIT: The following is an example of how you can append a number behind your id

innerHTML = `
    <div class="card-header">
       <h4 id="serverName` + 1 + `" class="my-0 font-weight-normal"></h4>
    </div>
    <div class="card-body">
       <h1 id="serverPrice" class="card-title pricing-card-title"></h1>
       <p id="serverTraits" class="list-unstyled mt-3 mb-4"></p>
    </div>`;

Leave a Reply

Your email address will not be published. Required fields are marked *