一、每个DOM节点都有一个nodeType属性,表示节点类型, NodeType一共有12种类型,我们可以通过遍历内置的Node构造函数获取
window.onload=function(){varstr="<table>";for(varkeyinNode){str+="<tr>";str+="<td>"+key+"</td><td>"+Node[key]+"</td>";str+="</tr>";}str+="</table>";document.body.innerHTML=str;}
其中,最常用的是1(元素节点) 和 3( 文本节点 ).可以结合childNodes做一个简单的应用
window.onload=function(){varoUl=document.getElementById("box");varcNodeList=oUl.childNodes;for(vari=0,len=cNodeList.length;i<len;i++){cNodeList[i].nodeType==1?cNodeList[i].style.backgroundColor='red':'';}}<ulid="box"><li>11111</li><li>22222</li><li>33333</li></ul>
上例,给li加背景颜色, childeNodes在chrome和FF下会区分元素节点和文本节点. 所以为了在chrome和FF下加上背景颜色,
需要nodeType = 1判断为元素节点,才能加上背景颜色
二、nodeName和nodeValue属性
如果是元素, nodeName就是标签名称, nodeValue为null, 如果是文本节点,自然就是空
window.onload=function(){varoUl=document.getElementById("box");varcNodeList=oUl.childNodes;for(vari=0,len=cNodeList.length;i<len;i++){console.log(cNodeList[i].nodeName,cNodeList[i].nodeValue);}}
三、每个节点都有一个childNodes属性,保存的是当前节点下面的所有子节点,其中保存着一个nodeList对象,nodeList是一种类数组结构,
有两种方法可以获取需要的子元素
数组索引
item方法
varoUl=document.getElementById("box");varcNodeList=oUl.childNodes;console.log(cNodeList[0]);console.log(cNodeList.item(0));
如果这个nodeList需要使用数组方法,他不能直接调用,需要转成数组方式
console.log( cNodeList.slice( 0, 1 ) ); 这样使用,会报错. 应该先转成数组,可以采用以下两种方式:
1//varaNode=[].slice.call(cNodeList,0);2varaNode=Array.prototype.slice.call(cNodeList,0);3console.log(aNode);
在IE8及其更老的版本,不支持这两种方式,只能使用for循环遍历
try{varaNode=[];aNode=Array.prototype.slice.call(cNodeList,0);}catch(e){for(vari=0,len=cNodeList.length;i<len;i++){aNode.push(cNodeList[i]);}}console.log(aNode);
四、兄弟节点、第一个子节点、最后一个子节点、父节点(parentNode),子节点(children)
这里一个有4组属性,IE和Chrome,FF支持的属性分别如下
在IE下是支持firstChild,lastChild,nextSibling,previousSibling
在Chrome和FF下支持:firstElementChild,lastElementChild,nextElementSibling,previousElementSibling
如果需要兼容,我们可以采用短路表达式:
window.onload=function(){varaDiv=document.getElementsByTagName("div");(aDiv[2].previousElementSibling||aDiv[2].previousSibling).style.color='red';(aDiv[1].nextElementSibling||aDiv[1].nextSibling).style.color='green';(document.body.firstElementChild||document.body.firstChild).style.color='blue';(document.body.lastElementChild||document.body.lastChild).style.color='orange';}<div>ghostwu1</div><div>ghostwu2</div><div>ghostwu3</div><div>ghostwu4</div>
parentNode的小应用,隐藏当前a元素对应的li元素
window.onload=function(){varaHref=document.getElementsByTagName("a");for(vari=0,len=aHref.length;i<len;i++){aHref[i].onclick=function(){this.parentNode.style.display='none';}}}<ul><li><ahref="javascript:;">1111</a><ahref="javascript:">隐藏</a></li><li><ahref="javascript:;">2222</a><ahref="javascript:;">隐藏</a></li><li><ahref="javascript:;">3333</a><ahref="javascript:;">隐藏</a></li></ul>
children的小应用,隔行变色
window.onload=function(){varoDiv=document.querySelector("#box");varaP=oDiv.children;aP=[].slice.call(aP);aP.forEach(function(el,key){el.style.backgroundColor=(key%2==0?'red':'green');},this);}<divid="box"><p></p><p></p><p></p><p></p><p></p><p></p></div>