创建DOM元素
createElement(标签名) 创建一个节点
appendChild(节点) 追加一个节点
例子:为ul插入li
插入元素
insertBefore(节点, 原有节点) 在已有元素前插入
例子:倒序插入li
删除DOM元素
removeChild(节点) 删除一个节点
例子:删除li
<script> window.onload=function() { var btn= document.getElementById("btn"); var txt1= document.getElementById("txt1"); var oul= document.getElementById("oul"); btn.onclick=function() { var oli=document.createElement("li"); oli.innerHTML=txt1.value; var lis=oul.getElementsByTagName("li"); if(lis.length>0) { oul.insertBefore(oli,lis[0]) } else { oul.appendChild(oli) } } } </script> </head> <body> <input type="text" id="txt1" /><br /> <ul id="oul"> </ul> <input type="button" id="btn" value="添加" /> </body>
删除节点
<script> window.onload=function () { var aA=document.getElementsByTagName('a'); var oUl=document.getElementById('ul1'); for(var i=0;i<aA.length;i++) { aA[i].onclick=function () { oUl.removeChild(this.parentNode); }; } }; </script> </head> <body> <ul id="ul1"> <li>asfasd <a href="javascript:;">删除</a></li> <li>5645 <a href="javascript:;">删除</a></li> <li>ghdfjgj <a href="javascript:;">删除</a></li> <li>mvbnmvnb <a href="javascript:;">删除</a></li> </ul> </body
各行变色
tBodies、tHead、tFoot、rows、cells
<script> window.onload=function () { var oTab=document.getElementById('tab1'); var oldColor=''; console.log(oTab.tBodies[0].rows.length) for(var i=0;i<oTab.tBodies[0].rows.length;i++) { oTab.tBodies[0].rows[i].onmouseover=function () { oldColor=this.style.background; this.style.background='green'; }; oTab.tBodies[0].rows[i].onmouseout=function () { this.style.background=oldColor; }; if(i%2) { oTab.tBodies[0].rows[i].style.background=''; } else { oTab.tBodies[0].rows[i].style.background='#CCC'; } } } </script> </head> <body> <table id="tab1" border="1" width="500"> <thead> <td>ID</td> <td>姓名</td> <td>年龄</td> </thead> <tbody> <tr> <td>1</td> <td>Blue</td> <td>27</td> </tr> <tr> <td>2</td> <td>张三</td> <td>23</td> </tr> <tr> <td>3</td> <td>李四</td> <td>28</td> </tr> <tr> <td>4</td> <td>王五</td> <td>25</td> </tr> <tr> <td>5</td> <td>张伟</td> <td>24</td> </tr> </tbody> </table> </body>