javascript每日一练(三)——DOM一

时间:2021-08-16 14:31:08

一、Dom基础

  childNodes(有兼容问题),children  nodeType  getAttribute()  firstChild,lastChild,previousSilbing,nextSilbing(有兼容问题)

  offsetParent,parentNode

 <!doctype html>
 <html>
 <head>
 <meta charset="utf-8">
 <title>无标题文档</title>
 <script>
 window.onload = function(){
     var oUl = document.getElementById('ul1');
     var aLi = oUl.childNodes;

     //1.childNodes
     //alert(oUl.childNodes.length);    //chrome 7 ie 3  有兼容问题,标准浏览器下会获取包括文本节点

     //2.nodeType:    1,元素节点    3,文本节点
     /*for(var i=0;i<aLi.length;i++){
         if(aLi[i].nodeType==1){
             aLi[i].style.background = 'red';
         }
     }*/

     //3.children    无兼容问题
     //alert(oUl.children.length);    //3

     //4.Dom方式获取元素属性
     //alert(oUl.getAttribute('id'));

     //5.firstChild    lastChild    有兼容问题
     //alert(oUl.firstChild);    //chrome:object Text        ie:object HTMLElement
     //var oFirst = oUl.firstElementChild || oUl.firstChild;
     //oFirst.style.background = 'red';

     //6.兄弟节点 有兼容问题(同上) nextSilbing    nextElementSilbing    previousSilbing    previousElementSilbing
     //oUl.nextSibling.style.background = 'red';

     //7.offsetParent获取元素基于定位的父级
     /*oUl.onclick = function(){
         alert(this.offsetParent.tagName);    //body
     };*/

     //8.parentNode    获取元素的父节点
     //alert(oUl.parentNode.tagName);    //body

     //9.getByClass
     var aBox = getByClass(document.body, 'box');

     for(var i=0;i<aBox.length;i++){
         aBox[i].style.background = 'red';
     }

 };

 function getByClass(oParent, sClass){
     var aEle = oParent.getElementsByTagName('*');
     var aResult = [];
     var i = 0;

     for(i=0;i<aEle.length;i++){
         if(aEle[i].className == sClass){
             aResult.push(aEle[i]);
         }
     }

     return aResult;
 }
 </script>
 </head>

 <body>
 <p>p1</p>
 <ul id="ul1">
     <li></li>
     <li class="box"></li>
     <li></li>
 </ul>
 <p class="box">p2</p>
 </body>
 </html>