一、Dom基础
childNodes(有兼容问题),children nodeType getAttribute() firstChild,lastChild,previousSilbing,nextSilbing(有兼容问题)
offsetParent,parentNode
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>无标题文档</title> 6 <script> 7 window.onload = function(){ 8 var oUl = document.getElementById('ul1'); 9 var aLi = oUl.childNodes; 10 11 //1.childNodes 12 //alert(oUl.childNodes.length); //chrome 7 ie 3 有兼容问题,标准浏览器下会获取包括文本节点 13 14 //2.nodeType: 1,元素节点 3,文本节点 15 /*for(var i=0;i<aLi.length;i++){ 16 if(aLi[i].nodeType==1){ 17 aLi[i].style.background = 'red'; 18 } 19 }*/ 20 21 //3.children 无兼容问题 22 //alert(oUl.children.length); //3 23 24 //4.Dom方式获取元素属性 25 //alert(oUl.getAttribute('id')); 26 27 //5.firstChild lastChild 有兼容问题 28 //alert(oUl.firstChild); //chrome:object Text ie:object HTMLElement 29 //var oFirst = oUl.firstElementChild || oUl.firstChild; 30 //oFirst.style.background = 'red'; 31 32 //6.兄弟节点 有兼容问题(同上) nextSilbing nextElementSilbing previousSilbing previousElementSilbing 33 //oUl.nextSibling.style.background = 'red'; 34 35 //7.offsetParent获取元素基于定位的父级 36 /*oUl.onclick = function(){ 37 alert(this.offsetParent.tagName); //body 38 };*/ 39 40 //8.parentNode 获取元素的父节点 41 //alert(oUl.parentNode.tagName); //body 42 43 //9.getByClass 44 var aBox = getByClass(document.body, 'box'); 45 46 for(var i=0;i<aBox.length;i++){ 47 aBox[i].style.background = 'red'; 48 } 49 50 }; 51 52 function getByClass(oParent, sClass){ 53 var aEle = oParent.getElementsByTagName('*'); 54 var aResult = []; 55 var i = 0; 56 57 for(i=0;i<aEle.length;i++){ 58 if(aEle[i].className == sClass){ 59 aResult.push(aEle[i]); 60 } 61 } 62 63 return aResult; 64 } 65 </script> 66 </head> 67 68 <body> 69 <p>p1</p> 70 <ul id="ul1"> 71 <li></li> 72 <li class="box"></li> 73 <li></li> 74 </ul> 75 <p class="box">p2</p> 76 </body> 77 </html>