0

Any idea How can I create the following div structure using JavaScript or JQuery, then i would like to append this structure to a div with a class = "grid"

<div class="grid-item grid-item--width">
 <div class="card">
   <div class="card-body">
      <div class="d-flex flex-row justify-content-between">
        <div>
           <p class="h5">User Name</p>
           <p class="h5">Level</p>
        </div>
        <div>
           <p class="h5">Category</p>
        </div>
     </div>
    <img class="card-img-bottom" src="hands.jpg"
    alt="Card image cap" style="width:344px">
    <p class="card-text">This is a wider card</p>
    <div class="d-flex flex-row justify-content-between">
       <div>
         <p class="h5">Location</p>
       </div>
       <div>
         <p class="h5">Life Time</p>
       </div>
    </div>
   </div>
   </div>
 </div> 

Appreciate any help

2 Answers 2

1

Pure JS is the fastest way, just create a string from all required html code and append it to innerHTML of the element you want, see snippet:

var divend = '</div>';
var divstart = '<div>';
var pclass5 = '<p class="h5">';
var pend = '</p>'

var grid_item = '<div class="grid-item grid-item--width"><div class="card"><div class="card-body">'+
 '<div class="d-flex flex-row justify-content-between">' + divstart+ pclass5+'User Name'+pend+ pclass5+
 'Level'+pend+ divend+ divstart+ pclass5+'Category'+pend + divend + divend+
    '<img class="card-img-bottom" src="hands.jpg" alt="Card image cap" style="width:344px">'+
    '<p class="card-text">' + 'This is a wider card'+ pend+  '<div class="d-flex flex-row justify-content-between">'+  divstart+  pclass5+'Location'+pend+  divend+ divstart+
         pclass5+'Life Time'+pend+ divend+  divend+ divend+ divend+ divend;
		 

 var grids = document.getElementsByClassName('grid');
// add for all elements with class == grid
 [...grids].forEach(grid=>{grid.innerHTML += grid_item;});
<div class='grid'></div>

P.s. if you have a lot of elements with class name grid, instead of forEach, use a normal for(){} loop, it is about twice faster performance wise depending on the browser.

Sign up to request clarification or add additional context in comments.

Comments

0

JQuery .append() and his family [ appendTo(), .prepend() ] is your friends.

var
new_HTML_cod = "<div class=\"grid-item grid-item--width\">";
new_HTML_cod += " <div class=\"card\">";
new_HTML_cod += "  <div class=\"card-body\">";
//...
$(new_HTML_cod).appendTo($('.grid'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.