改变文档结构的方法(5种)
1.在元素的最后面追加子元素
语法:父元素.appendChild(子元素对象)
案例:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 7 <style> 8 .main{ 9 width: 600px; 10 height: 300px; 11 margin: 0 auto; 12 display: flex; 13 background-color: #5d656b; 14 } 15 .child{ 16 width: 200px; 17 height: 400px; 18 text-align: center; 19 } 20 .c1{ 21 background-color:#e8e318; 22 } 23 .c2{ 24 background-color: darkgoldenrod; 25 } 26 .c3{ 27 background-color: chartreuse; 28 } 29 #d1{ 30 width: 200px; 31 height: 300px; 32 } 33 34 </style> 35 36 </head> 37 <body> 38 39 <h1>点击相应的美女进行分类</h1> 40 <img src="img/12347.jpg" id="d1"/> 41 42 <div class="main"> 43 <div class="child c1">少女</div> 44 <div class="child c2">萝莉</div> 45 <div class="child c3">御女</div> 46 </div> 47 48 <script type="application/javascript"> 49 var main=document.querySelector(".main") 50 var h1=document.querySelector("h1") 51 var d1=document.querySelector("#d1") 52 53 main.onclick=function(e){ 54 console.log(e) 55 e.target.appendChild(d1) 56 } 57 58 </script> 59 60 61 </body> 62 </html>
2.在什么元素前面追加元素
语法:父元素.insertBefore(插入的元素对象,参考对象)
案例:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <ul> <li class="l1"> <h1>美女类型1</h1> </li> <li class="l2"> <h1>美女类型2</h1> </li> <li class="l3"> <h1>美女类型3</h1> </li> </ul> <script type="application/javascript"> var girl=document.createElement("img") girl.src="img/12347.jpg" girl.style.width="200px" girl.style.height="atuo" var l2=document.querySelector(".l2") var h1=document.querySelector(".l2 h1") l2.insertBefore(girl,h1) </script> </body> </html>
3.替换元素
语法:父元素.replaceChild(替换的元素对象,被替换的元素对象)
案例:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <div class="main"> 9 <img src="img/1232.jpg" class="oldimg"/> 10 </div> 11 12 <script type="application/javascript"> 13 var oldimg=document.querySelector(".oldimg") 14 var main=document.querySelector(".main") 15 var newimg=document.createElement("img") 16 newimg.src="img/12347.jpg" 17 18 main.replaceChild(newimg,oldimg) 19 20 21 </script> 22 </body> 23 </html>
4.删除元素
语法:父元素.removeChild(删除元素对象)
案例:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <h1>helloworld</h1> 9 10 <script type="application/javascript"> 11 12 var h1=document.querySelector("h1") 13 //document.body.removeChild(h1) 14 15 //便捷删除元素对象的方式 16 //语法:元素对象.parentElement.removeChild(元素对象) 17 h1.parentElement.removeChild(h1) 18 19 </script> 20 </body> 21 </html>
5.创建元素
语法:document.createElement("元素对象的标签名称")
注:创建元素并没有显示到页面上,都需要上面的qppendChild,insertBefore,replaceChild的任意一种来完成插入到页面结构中