DOM基础

来源:互联网 发布:windows直接进入桌面 编辑:程序博客网 时间:2024/06/16 08:22

·DOM基础-1

子节点:childNodes ,只算第一层的

alert(oUl.childNodes.length);
节点类型:nodeType  与childNodes配合解决兼容问题

alert(oUl.childNodes[1].nodeType);

var oUl = document.getElementById('ul1');for(var i=0;i<oUl.childNodes.length;i++){//nodeType==3->文本节点//nodeType==1->元素节点if(oUl.childNodes[i].nodeType==1){oUl.childNodes[i].style.background='red';}}
子节点:children,与childNodes相似,但是不会出现问题

alert(oUl.children.length);
父节点:parentNode

var oUl = document.getElementById('ul1');alert(oUl.parentNode);
父节点应用:实现点击隐藏的功能

window.onload=function (){var aA = document.getElementsByTagName('a');for(var i=0;i<aA.length;i++)  {aA[i].onclick=function (){this.parentNode.style.display='none';};}};
offsetParent:寻找父节点,获取元素在页面上的实际位置,position设置不同就会不同

<script>window.onload=function (){var oDiv2=document.getElementById('div2');alert(oDiv2.offsetParent);};</script>

·DOM基础-2

firstChild、lastChild  (高版本浏览器有兼容问题)
firstChildElementChild、lastElementChild(低版本浏览器有兼容问题)

//IE6-8浏览器可以用oUl.firstChild.style.background='red';//高级浏览器可以用oUl.firstElementChild.style.background='red';

使用if判断解决兼容问题

if(oUl.firstElementChild){oUl.firstElementChild.style.background='red';}else{oUl.firstChild.style.background='red';}

·操纵元素属性

获取:getAttribute(名称)
设置:setAttribute(名称,值) (第三种操作属性的方法)
删除:removeAttribute(名称)

window.onload=function(){var oTxt = document.getElementById('txt1');var oBtn = document.getElementById('btn1');oBtn.onclick = function(){//三个语句设置属性效果一样//oTxt.value='asdas';//oTxt['value']='asdas';oTxt.setAttribute('value','asdas');};};
alert(oBtn.getAttribute('value')); //获取
alert(oBtn.removeAttribute('value')); //删除

·DOM元素灵活查找
用className选择元素

window.onload=function (){var oUl = document.getElementById('ul1');var aLi = oUl.getElementsByTagName('li');for(var i=0;i<aLi.length;i++){if(aLi[i].className=='box'){aLi[i].style.background='red';}}};
封装成函数,通配符*的使用,arr.push()数组尾部添加

function getByClass(oParent,oClass){var aResult = [];var aEle = oParent.getElementsByTagName('*');for(var i=0;i<aEle.length;i++){if (aEle[i].className==oClass) {aResult.push(aEle[i]);}}return aResult;}window.onload=function (){var oUl = document.getElementById('ul1');var aBox = getByClass(oUl,'box');for(var i=0;i<aBox.length;i++){aBox[i].style.background='red';}};

























原创粉丝点击