最近寫代碼時須要獲取符合某些條件的節點子元素,用firstChild之類的方法會包含文本節點,因此包裝了一個簡單的類:node
1 //子元素遍歷器 2 function ElementWalker(node) { 3 if(typeof node === 'string') 4 node = document.getElementById(node); 5 this.node = node; 6 } 7 ElementWalker.prototype = { 8 //獲取第一個指定tagName的子元素,若是tagName沒定義,則返回第一個子元素 9 first: function(tagName) { 10 if((typeof tagName === 'undefined') && this.node.firstElementChild) { 11 return new ElementWalker(this.node.firstElementChild); 12 } 13 for(i = 0; i < this.node.childNodes.length; i++) { 14 if(this.checkChild(i,tagName)) { 15 return new ElementWalker(child); 16 } 17 } 18 }, 19 //獲取最後一個指定tagName的子元素,若是tagName沒定義,則返回最後一個子元素 20 last: function(tagName) { 21 if((typeof tagName === 'undefined') && this.node.lastElementChild) { 22 return new ElementWalker(this.node.lastElementChild); 23 } 24 for(i = parent.childNodes.length - 1; i >= 0; i--) { 25 var child = this.node.childNodes[i]; 26 if(this.checkChild(child,tagName)) { 27 return new ElementWalker(child); 28 } 29 } 30 }, 31 //返回全部指定tagName的子元素,若是tagName沒定義,則返回全部子元素 32 all: function(tagName) { 33 var children = []; 34 for(i = 0; i < this.node.childNodes.length; i++) { 35 var child = this.node.childNodes[i]; 36 if(this.checkChild(child,tagName)) { 37 children.push(new ElementWalker(child)); 38 } 39 } 40 return children; 41 }, 42 //校驗child是不是指定tagName的元素 43 checkChild : function(child,tagName) { 44 var isOK = (typeof tagName === 'undefined') && child.nodeType == 1; 45 isOK = isOK || (child.tagName && child.tagName.toLowerCase() === tagName); 46 return isOK; 47 } 48 }