使用JavaScript

时间:2019-02-08 09:07:14

标签: javascript jquery

是否可以使用JavaScript在现有的div中创建新的div?

我希望发生以下情况:

  1. 使用class="three"创建一个新的div并将其放在div class="one"内。
  2. 使用class="text"创建一个新的div并将其放在class="three"内,并添加文本“ this is sample text”。

最终结果应如下所示:

enter image description here

.two{
  width:700px;
  height: 600px;
  background-color: yellow;
}

.three{
  width:300px;
  height: 200px;
  transform: translate(50%, -250%);
  background-color: red;
}
.text{
  text-align: right;
  transform: translate(-5%, 440%);
  color: black;
}
<div class="one">
  <div class="two">
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

// get a reference to the first div by using its class as search path
var divOne = document.querySelector('.one');
// create a new element
var divThree= document.createElement('DIV');
// add a class 'three' to a newly created element
divThree.classList.add('three');
// and add a newly created element to divOne
divOne.appendChild(divThree);

// now create a div for text, set its class to 'text' and append it to divThree
var txt = document.createElement('DIV');
txt.classList.add('text');
txt.innerHTML = 'this is sample text';
divThree.appendChild(txt);
.two{
  width:700px;
  height: 600px;
  background-color: yellow;
}

.three{
  width:300px;
  height: 200px;
  transform: translate(50%, -250%);
  background-color: red;
}
.text{
  text-align: right;
  transform: translate(-5%, 440%);
  color: black;
}
<div class="one">
  <div class="two">
  </div>
</div>

答案 1 :(得分:0)

使用jquery,您可以编写以下代码。

$(document).ready(function(){
    $(".one").html("<div class='three'><div class='text'>This is a sample text</div><div>");
});