<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>创建li</title> <script> window.onload=function() { //获取按钮 var oBtn=document.getElementById(‘btn1‘); //获取文本 var oTxt=document.getElementById(‘txt1‘); //获取ul var oUl=document.getElementById(‘ul1‘); oBtn.onclick=function() { //在do里创建li var oLi=document.createElement(‘li‘); //文本框的值赋予oli oLi.innerHTML=oTxt.value; //父类添加子节点 oUl.appendChild(oLi); //清空txt里的值 oTxt.value=‘‘; } } </script> </head> <body> <input id="txt1" type="text" /> <input id="btn1" type="button" value="创建Li"/> <ul id="ul1"> <li>aaa</li> </ul> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>父.insertBefore(子节点,谁之前)</title> <script> window.onload=function() { var oBtn=document.getElementById(‘btn1‘); var oTxt=document.getElementById(‘txt1‘); var oUl=document.getElementById(‘ul1‘); oBtn.onclick=function() { //创建个li var oLi=document.createElement(‘li‘); //获取ul里的li var aLi=oUl.getElementsByTagName(‘li‘); //把otxt的值赋予oli oLi.innerHTML=oTxt.value; //插入到oul里ali[0]坐标之前; oUl.insertBefore(oLi, aLi[0]); oTxt.value=‘‘; } } </script> </head>
原文:http://www.cnblogs.com/hack-ing/p/5555627.html