Cliff Anderssen
Cliff Anderssen

Reputation: 63

How to dynamically add div in JavaScript?

I have the following code;

<div class="col l3 m6 w3-margin-bottom">
  <div class="display-container">
    <div class="w3-display-topleft w3-black w3-padding">Brick House</div>
    <img src="image.jpg" alt="House" style="width:99%">
  </div>
</div>

I want to be able to dynamically add multiples of this through the JavaScript code. Please I am not very proficient in JavaScript and anything helps.

Upvotes: 0

Views: 195

Answers (3)

Sci Ranch
Sci Ranch

Reputation: 115

This is a simple method using the new template strings.

You can even put a variable value inside by doing ${myVar} inside of the template string.

// This is code that you can change
let code = `
<div class="col l3 m6 w3-margin-bottom">
  <div class="display-container">
    <div class="w3-display-topleft w3-black w3-padding">Brick House</div>
    <img src="image.jpg" alt="House" style="width:99%">
  </div>
</div>`;

// You can append it to an element in HTML
document.getElementById('id').innerHTML+=code;

Upvotes: 0

Da Mahdi03
Da Mahdi03

Reputation: 1608

Using jQuery:

$(document).append('<div class="col l3 m6 w3-margin-bottom"> <div class="display-container"> <div class="w3-display-topleft w3-black w3-padding">Brick House</div> <img src="image.jpg" alt="House" style="width:99%"> </div> </div>');

Upvotes: 1

Joe Iddon
Joe Iddon

Reputation: 20414

Get a reference to the DOM element in your code (whether it be by id, class name, tag name, etc.), then append this is as a string to the innerHTML attribute:

let el = document.getElementById('id');
el.innerHTML += '
<div class="col l3 m6 w3-margin-bottom">
  <div class="display-container">
    <div class="w3-display-topleft w3-black w3-padding">Brick House</div>
    <img src="image.jpg" alt="House" style="width:99%">
  </div>
</div>
';

Upvotes: 0

Related Questions