Luiz Adorno
Luiz Adorno

Reputation: 127

How to dynamically create these HTML elements using JS

enter image description here I want to create this layout, dynamically to create a list of it, getting the data from database and populate.

Here's the layout's code:

<div class="card-body">
  <!-- person -->
  <div class="row" id="img_div">
    <div class="col-12 col-sm-12 col-md-2 text-center">
      <img src="http://placehold.it/120x80" alt="prewiew" width="120" height="80">
    </div>
    <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">
      <h4 class="product-name"><strong>Person Name</strong></h4>
      <h4>
        <small>state</small>
      </h4>
      <h4>
        <small>city</small>
      </h4>
      <h4>
        <small>zip</small>
      </h4>
    </div>
    <div class="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row">


    </div>
  </div>
  <!-- END person -->
  <!-- person -->
  <div class="row" id="img_div">
    <div class="col-12 col-sm-12 col-md-2 text-center">
      <img src="http://placehold.it/120x80" alt="prewiew" width="120" height="80">
    </div>
    <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">
      <h4 class="product-name"><strong>Person Name</strong></h4>
      <h4>
        <small>state</small>
      </h4>
      <h4>
        <small>city</small>
      </h4>
      <h4>
        <small>zip</small>
      </h4>
    </div>
    <div class="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row">

    </div>
  </div>
  <!-- END person -->
</div>

For recap, I want to replicate the "person" layout dynamically to populate with database data

Is there any library of Javascript that can do the job?

Upvotes: 0

Views: 1042

Answers (6)

ksav
ksav

Reputation: 20821

If your data is an array of objects, you can iterate through it to generate the HTML before inserting into the DOM.*


Here I've used a helper function to generate the HTML of each individual person card (personCardHtml). It returns a template literal which fills in the person's details in the correct spot within the HTML.

I've used Array.reduce on the array of people to generate a single string of HTML of all the person cards together.

Then I've used insertAdjacentHTML to insert that html string into <div id="persons-container"></div>

const people = [{"name": "Henrietta Marsh","state": "Northern Mariana Islands","city": "Ernstville","zip": 7226},{"name": "Sandy Copeland","state": "Wyoming","city": "Hobucken","zip": 4594},{"name": "Logan Frank","state": "Puerto Rico","city": "Talpa","zip": 8670}]

const personCardHtml = (person) => {
  return `<div class="card-body">
  <!-- person -->
  <div class="row" id="img_div">
    <div class="col-12 col-sm-12 col-md-2 text-center"><img src="http://placehold.it/120x80?text=${person.name}" alt="prewiew" width="120" height="80"></div>
    <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">
      <h4 class="product-name"><strong>${person.name}</strong></h4>
      <h4><small>${person.state}</small></h4>
      <h4><small>${person.city}</small></h4>
      <h4><small>${person.zip}</small></h4>
    </div>
  </div>
  <!-- END person -->`
}
const reducer = (accumulator, currentValue) => accumulator + personCardHtml(currentValue);
const personsHtml = people.reduce(reducer, '')
const container = document.querySelector('#persons-container')
container.insertAdjacentHTML('beforeend', personsHtml);
<div id="persons-container"></div>


* It is best practice to keep DOM manipulations to a minimum if you want your page to be performant.

Upvotes: 3

Sifat Haque
Sifat Haque

Reputation: 6057

You can use template literals in js to solve your issue.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>JS Bin</title>
  </head>
  <body>
    <div id="root"></div>
    <script>
      let root = document.getElementById("root");
      const persons = [
        {
          name: "person1",
          state: "person1_state",
          city: "person1_city",
          zip: "person1_zip"
        },
        {
          name: "person2",
          state: "person2_state",
          city: "person2_city",
          zip: "person2_zip"
        },
        {
          name: "person3",
          state: "person3_state",
          city: "person3_city",
          zip: "person3_zip"
        },
        {
          name: "person4",
          state: "person4_state",
          city: "person4_city",
          zip: "person4_zip"
        }
      ];

      const renderPerson = persons => {
        let data = ``;
        persons.forEach(person => {
          data += `
            <div class="card-body">
                <!-- person -->
                <div class="row" id="img_div">
                    <div class="col-12 col-sm-12 col-md-2 text-center">
                        <img src="http://placehold.it/120x80" alt="prewiew" width="120" height="80">
                    </div>
                    <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">
                        <h4 class="product-name"><strong>${person.name}</strong></h4>
                        <h4>
                            <small>${person.state}</small>
                        </h4>
                        <h4>
                            <small>${person.city}</small>
                        </h4>
                        <h4>
                            <small>${person.zip}</small>
                        </h4>
                    </div>
                <div class="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row">


                    </div>
                </div>
                <!-- END person -->
            </div>`;
        });
        return data;
      };
      
      
      
      root.innerHTML = renderPerson(persons);
      
      
      
    </script>
  </body>
</html>

Upvotes: 1

Fatema
Fatema

Reputation: 36

With pure javascript you can do this. Demo: https://codepen.io/ftj07/pen/KKppeaL

 <div class="row" id="designId"><div>

  <input type="button" onClick="generateList()" value="generateList" /> 
function generateList() {
  var personList = [
     { name: "Abc", state: "41", city: "USA", zip: "124" },
     { name: "Abc", state: "41", city: "USA", zip: "124" },
     { name: "Abc", state: "41", city: "USA", zip: "124" },
     { name: "Abc", state: "41", city: "USA", zip: "124" },
     { name: "Abc", state: "41", city: "USA", zip: "124" }
  ]
  let design = "";
  for(let item of personList){
    design += `
  <div class="col-12 col-sm-12 col-md-2 text-center">
   <img src="http://placehold.it/120x80" alt="prewiew" width="120" height="80">
  </div>
  <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">
   <h4 class="product-name"><strong>${item.name}</strong></h4>
   <h4>
    <small>${item.state}</small>
   </h4>
   <h4>
    <small>${item.city}</small>
   </h4>
   <h4>
    <small>${item.zip}</small>
   </h4>
  </div>  `
  }
  console.log("da",design)
  document.getElementById("designId").innerHTML  = design;
}

Upvotes: 1

Prabha Karan
Prabha Karan

Reputation: 11

Use the following code for creating dynamic element and add attribute to that element.

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
  border: 1px solid black;
  margin-bottom: 10px;
}
</style>
</head>
<body>

<p>Click the button to create a P element with some text, and append it to DIV.</p>

<div id="myDIV">
A DIV element
</div>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  var para = document.createElement("P");
  para.innerHTML = "This is a paragraph.";
  document.getElementById("myDIV").appendChild(para);
}
</script>

</body>
</html>

Upvotes: 1

Sandesh Mankar
Sandesh Mankar

Reputation: 699

I Will generate design the same as you mention in the above image. add CSS in your file. dynamically javascript creates multiple data.

$(document).ready(function(){
  
  for(i=0;i<10;i++){
  $("#allPerson").append(`<div class="row" id="img_div">
    <div class="col-12 col-sm-12 col-md-2 text-center person">
      <img src="http://placehold.it/120x80" alt="prewiew" width="120" height="80">
    </div>
    <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6 div">
      <h4 class="product-name"><strong>Person Name</strong></h4>
      <h4>
        <small>state</small>
      </h4>
      <h4>
        <small>city</small>
      </h4>
      <h4>
        <small>zip</small>
      </h4>
    </div>
    <div class="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row">
  </div>
  </div>`);
  }
  
});
.person{
  float:left;
  margin-right:10px;
}
#img_div{
  width:100%;
  margin:10px;
  float:left;
}
h4{
  margin:0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div class="card-body" id="allPerson">
  <!-- person -->

  <!-- END person -->
  <!-- person -->

  <!-- END person -->
  
</div>

Upvotes: 1

ellipsis
ellipsis

Reputation: 12152

You can use a for loop to append the HTML to the element of your choice. The i in the loop is the size of the elements received from the database

for(let i=1;i<10;i++)
{
document.querySelector('.card-body').innerHTML+=`<div class="row" id="img_div">
    <div class="col-12 col-sm-12 col-md-2 text-center">
      <img src="http://placehold.it/120x80" alt="prewiew" width="120" height="80">
    </div>
    <div id="text_div" class="col-12 text-sm-center col-sm-12 text-md-left col-md-6">
      <h4 class="product-name"><strong>Person`+i+`</strong></h4>
      <h4>
        <small>state</small>
      </h4>
      <h4>
        <small>city</small>
      </h4>
      <h4>
        <small>zip</small>
      </h4>
    </div>
    <div class="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row">
    </div>
  </div>
 `
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="card-body">
  <!-- person -->
  </div>

Upvotes: 1

Related Questions