1、childNodes:获取节点,不同浏览器表现不同;
IE:只获取元素节点;
非IE:获取元素节点与文本节点;
nodeType:节点类型 与childNodes配合使用;
解决方案:if(oUl.childNodes.nodeType == 1) { …}
2、children:获取元素节点,浏览器表现相同。
建议使用children。
3、parentNode:获取父元素,不存在兼容性问题。
例:隐藏父级:
var aLi=document.getElementsByTagName('a');
for(var i=0;i<aLi.length;i++){
aLi[i].onclick=function(){
this.parentNode.style.display='none';
}
}
4、offsetParent:获取第一个设置定位的父元素。
a,元素自身有fixed定位,offsetParent的结果为null:
当元素自身有fixed固定定位时,固定定位的元素相对于视口进行定位,此时没有定位父级, offsetParent的结果为null
firefox浏览器有兼容性问题
<div id="parent" style="position:fixed"></div>
<script>
//firefox并没有考虑固定定位的问题,返回<body>,其他浏览器都返回null
console.log(parent.offsetParent);
</script>
b,元素自身无fixed定位,且父级元素都未经过定位,offsetParent的结果为
<div id="parent"></div>
<script>
console.log(parent.offsetParent);//<body>
</script>
c,元素自身无fixed定位,且父级元素存在经过定位的元素,offsetParent的结果为离自身元素最近的经过定位的父级元素
复制代码
<div id="div0" style="position:absolute;">
<div id="div1" style="position:absolute;">
<div id='parent'></div>
</div>
</div>
<script>
console.log(parent.offsetParent); //<div id="div1">
</script>
d,元素的parentNode是null
console.log(document.body.offsetParent);//null
f,IE7-浏览器Bug
当元素本身经过绝对定位或相对定位,且父级元素无经过定位的元素时,IE7-浏览器下,offsetParent是
<div id="parent" style="position:absolute;"></div>
<script>
//IE7-浏览器返回<html>,其他浏览器返回<body>
console.log(parent.offsetParent);
</script>
----------------------------------------------------------------------------------------
<div id="parent" style="position:relative;"></div>
<script>
//IE7-浏览器返回<html>,其他浏览器返回<body>
console.log(parent.offsetParent);
</script>
----------------------------------------------------------------------------------------
<div id="parent" style="position:fixed;"></div>
<script>
//firefox并没有考虑固定定位的问题,返回<body>,其他浏览器都返回null
console.log(parent.offsetParent);
</script>