標籤:node length 整理 方法 function 操作 bsp previous tno
在複習javascript基礎的時候,整理了一下js中擷取節點的一些常用的方法,見代碼:
1 //js擷取下一個兄弟節點 2 function getNextSibling(eleObj){ 3 var next = eleObj.nextSibling; 4 if(next.nodeType == 3){ // 文本節點 5 return next.nextSibling; 6 } 7 return next; 8 } 9 //js擷取上一個兄弟節點10 function getPreviousSibling(eleObj){11 var pre = eleObj.previousSibling;12 if(pre.nodeType == 3){13 return pre.previousSibling;14 }15 return pre;16 }17 //js擷取所有子節點18 function getChildNodes(parentNode){19 var childs = [];20 for(var i=0; i<parentNode.childNodes.length; i++){21 if(parentNode.childNodes[i].nodeType == 1){ // 元素節點22 childs.push(parentNode.childNodes[i]);23 }24 }25 return childs;26 }27 28 //js擷取第一個子節點29 function getFirstChildNode(parentNode){30 var first = parentNode.firstChild;31 if(first.nodeType == 3){ // 文本節點32 return first.nextSibling;33 }34 return first;35 /*return parentNode.firstElementChild;*/36 }37 //js擷取最後一個子節點38 function getLastChildNode(parentNode){39 var last = parentNode.lastChild;40 if(last.nodeType == 3){41 return last.nextSibling;42 }43 return last;44 }
js dom操作擷取節點的一些方法