| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- .box{
- width: 400px;
- height: 400px;
- border:3px solid black;
- }
- .box1{
- width: 200px;
- height: 200px;
- background-color: red;
- }
- .box2{
- width: 200px;
- height: 200px;
- background-color: blue;
- }
- </style>
- </head>
- <body>
- <div class="box">
- <div class="box2"></div>
- </div>
- <button class="btn">add</button>
- <script>
- var oBtn = document.getElementsByClassName("btn")[0];
- var oBox = document.getElementsByClassName("box")[0];
- var oBox2 = document.getElementsByClassName("box2")[0];
- oBtn.onclick = function(){
- // oBox.innerHTML = "<div class=box1></div>"
- // createElement 创建新的元素
- var newElement = document.createElement("div");
- newElement.innerText = "hello";
- newElement.classList.add("box1");
- // console.log(newElement);
- // append 向当前元素最后添加一个新的元素
- // oBox.append(newElement);
- // insertBefore 也可以向元素内添加节点 后边两个参数第一个 你要插入元素 第二个插入到谁的前面
- oBox.insertBefore(newElement,oBox2);
- }
- </script>
- </body>
- </html>
|