1、在元素之前添加元素
<html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> <input type="text" id="txt1" /> <input type="button" id="btn1" value="创建" /> <ul id="ul1"></ul> <script> var obtn=document.getElementById('btn1'); var oul=document.getElementById('ul1'); var otxt=document.getElementById('txt1'); obtn.onclick=function() { var oli=document.createElement('li'); /*创建元素*/ var ali=oul.getElementsByTagName('li'); oli.innerHTML=otxt.value; if(ali.length>0) { oul.insertBefore(oli,ali[0]); /*在元素之前插入*/ } else { oul.appendChild(oli); } } </script> </body> </html>
2、在元素之后添加元素
<html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> <input type="text" id="txt1" /> <input type="button" id="btn1" value="创建" /> <ul id="ul1"></ul> <script> var obtn=document.getElementById('btn1'); var oul=document.getElementById('ul1'); var otxt=document.getElementById('txt1'); obtn.onclick=function() { var oli=document.createElement('li'); /*创建元素*/ oli.innerHTML=otxt.value; oul.appendChild(oli); /*把li作为一个子节点添加给父级ul*/ } </script> </body> </html>
3、删除元素
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> <ul id="ul1"> <li>blog.xinlvtian.com<a href="javascript:;">删除</a></li> <li>xinlvtian.com<a href="javascript:;">删除</a></li> <li>wwwxinlvtian.com<a href="javascript:;">删除</a></li> </ul> <script> var oa=document.getElementsByTagName('a'); var oul=document.getElementById('ul1'); for(var i=0;i<oa.length;i++) { oa[i].onclick=function() { oul.removeChild(this.parentNode); /*删除节点*/ } } </script> </body> </html>
4、文档碎片
<html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> <ul id="ul1"> </ul> <script> var oul=document.getElementById('ul1'); var ofrag=document.createDocumentFragment(); /*创建文档碎片*/ for(var i=0;i<10000;i++) /*创建10000个li*/ { var oli=document.createElement('li'); ofrag.appendChild(oli); //oul.appendChild(oli); /*没有创建文档碎片*/ } oul.appendChild(ofrag); /*文档碎片是针对低端的浏览器的,对于高端浏览器可能会降低性能*/ </script> </body> </html>