父级.removeChild(子节点);
父级.appendChild(子节点);
父级.insertBefore(子节点, 在谁之前);
创建元素:
1 <script> 2 window.onload = function(){ 3 var oBtn=document.getElementById('btn1'); 4 var oUl=document.getElementById('ul1'); 5 var oTxt=document.getElementById('txt1'); 6 7 oBtn.onclick=function (){ 8 var oli = document.createElement('li'); 9 var ali = document.getElementsByTagName('li'); 10 11 oli.innerHTML = oTxt.value; 12 if(ali.length>0){ 13 oUl.insertBefore(oli, ali[0]); 14 }else{ 15 oUl.appendChild(oli); 16 } 17 } 18 } 19 </script> 20 </head> 21 22 <body> 23 <input id="txt1" type="text"/> 24 <input id="btn1" type="button" value="创建li"/> 25 <ul id="ul1"> 26 </ul> 27 </body>
文档碎片的使用:
1 <script> 2 window.onload=function () 3 { 4 var oUl=document.getElementById('ul1'); 5 var oFrag=document.createDocumentFragment(); 6 7 for(var i=0;i<10000;i++) 8 { 9 var oLi = document.createElement('li'); 10 11 oFrag.appendChild(oLi); 12 } 13 14 oUl.appendChild(oFrag); 15 }; 16 17 </script> 18 </head> 19 20 <body> 21 <ul id="ul1"> 22 </ul>
childNodes nodeType
获取子节点
children parentNode
例子:点击链接,隐藏整个li
offsetParent
例子:获取元素在页面上的实际位置
firstChild、firstElementChild、lastChild 、lastElementChild的使用
1 <script> 2 window.onload=function () 3 { 4 var oUl=document.getElementById('ul1'); 5 6 //IE6-8 7 //oUl.firstChild.style.background='red'; 8 9 //高级浏览器 10 //oUl.firstElementChild.style.background='red'; 11 12 if(oUl.firstElementChild) 13 { 14 oUl.firstElementChild.style.background='red'; 15 } 16 else 17 { 18 oUl.firstChild.style.background='red'; 19 } 20 }; 21 </script> 22 </head> 23 24 <body> 25 <ul id="ul1"> 26 <li>1</li> 27 <li>2</li> 28 <li>3</li> 29 </ul> 30 </body>