JavaScript(4)
阿新 • • 發佈:2017-05-16
rtb 一個 back idt bsp pan ctype scrip asc
DOM操作
1、創建DOM元素
a、createElement(標簽名) ----創建一個節點
b、appendChild(節點) -----追加一個節點
例子:為ul插入li
代碼:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload = function (){ 8 9var oBtn = document.getElementById(‘btn1‘); 10 oUl = document.getElementById(‘ul1‘); 11 oBtn.onclick = function (){ 12 13 oLi = document.createElement(‘li‘);//創建節點 14 oUl.appendChild(oLi);//插入節點 15 }16 17 } 18 </script> 19 </head> 20 21 <body> 22 <input id="btn1" type="button" value="創建Li"/> 23 <ul id="ul1"> 24 25 </ul> 26 </body> 27 </html>
運行效果:
為li裏面加入內容:
代碼:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload = function (){ 8 9 var oBtn = document.getElementById(‘btn1‘); 10 oUl = document.getElementById(‘ul1‘); 11 var oText = document.getElementById(‘text1‘); 12 oBtn.onclick = function (){ 13 14 oLi = document.createElement(‘li‘);//創建節點 15 oLi.innerHTML = oText.value;//加入輸入的內容 16 oUl.appendChild(oLi);//插入節點 17 } 18 19 } 20 </script> 21 </head> 22 23 <body> 24 <input id="text1" type="text"/> 25 <input id="btn1" type="button" value="創建Li"/> 26 <ul id="ul1"> 27 28 </ul> 29 </body> 30 </html>
運行效果:
2、插入元素
a、insertBefore(節點,原有節點) ---在已有元素之前插入
--例子:倒序插入li
代碼:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload = function (){ 8 9 var oBtn = document.getElementById(‘btn1‘); 10 oUl = document.getElementById(‘ul1‘); 11 var oText = document.getElementById(‘text1‘); 12 aLi = document.getElementsByTagName(‘li‘); 13 oBtn.onclick = function (){ 14 15 oLi = document.createElement(‘li‘);//創建節點 16 oLi.innerHTML = oText.value;//賦值 17 oUl.insertBefore(oLi,aLi[0]);//插入元素 18 19 } 20 21 } 22 </script> 23 </head> 24 25 <body> 26 <input id="text1" type="text"/> 27 <input id="btn1" type="button" value="創建Li"/> 28 <ul id="ul1"> 29 30 </ul> 31 </body> 32 </html>
運行效果:
3、刪除DOM元素
a、removeChild(節點) ---刪除一個節點
--例子:刪除li
代碼:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload = function (){ 8 var oUl = document.getElementById(‘ul1‘); 9 var oA = document.getElementsByTagName(‘a‘); 10 for(var i=0;i<oA.length;i++){ 11 12 oA[i].onclick = function (){ 13 oUl.removeChild(this.parentNode); 14 } 15 } 16 17 } 18 </script> 19 </head> 20 21 <body> 22 <ul id="ul1"> 23 <li>aaaaaaa<a href="javascript:;">刪除</a></li> 24 <li>bbbbbbb<a href="javascript:;">刪除</a></li> 25 <li>ccccccc<a href="javascript:;">刪除</a></li> 26 <li>ddddddd<a href="javascript:;">刪除</a></li> 27 <li>eeeeeee<a href="javascript:;">刪除</a></li> 28 <li>fffffff<a href="javascript:;">刪除</a></li> 29 <li>ggggggg<a href="javascript:;">刪除</a></li> 30 </ul> 31 </body> 32 </html>
運行效果:
JavaScript(4)