Search code examples
javascripthtmldomappendchild

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?


Solution

  • 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>