点滴积累【JS】---JS小功能(createElement和insertBefore添加div下面的节点)
效果:
代码:
<head runat="server"> <title></title> <script type="text/javascript"> window.onload = function () { var oul = document.getElementById('ull'); var obtn = document.getElementById('btn'); var ot1 = document.getElementById('t1'); var obtnRemove = document.getElementById('btn1'); obtn.onclick = function () { var oli = document.createElement('li'); var ali = oul.getElementsByTagName('li'); if (ali.length > 0) { oul.insertBefore(oli, ali[0]); } else { oul.appendChild(oli); } oli.innerHTML = ot1.value; //删除 obtnRemove.onclick = function () { for (var i = 0; i < ali.length; i++) { oul.removeChild(ali[0]); } } } }; </script> </head> <body> <form id="form1" runat="server"> <div> <input type="text" id="t1" /> <input type="button" id="btn" value="添加元素"> <input type="button" id="btn1" value="删除元素"> <ul id="ull"> </ul> </div> </form> </body>