如何在JavaScript中动态添加div?

时间:2018-09-02 17:57:27

标签: javascript html

我有以下代码;

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

我希望能够通过JavaScript代码动态添加此内容的倍数。请我不是很精通JavaScript,任何帮助。

3 个答案:

答案 0 :(得分:1)

使用jQuery:

<form action="/action_page.php">
   First name: 
   <input type="text" name="fname" value="John" disabled ><br>
   Last name:
   <input type="text" name="lname" value="Doe"><br>
   <input type="submit" value="Submit form">
</form>

答案 1 :(得分:0)

在您的代码中获取对DOM元素的引用(无论是通过id,类名,标记名等),然后将其作为字符串附加到innerHTML属性中:

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>
';

答案 2 :(得分:0)

这是使用新模板字符串的简单方法。

您甚至可以通过在模板字符串中进行${myVar}来放置变量值。

// 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;