DOM 的 childNodes 會把文字節點、註解節點一起算進來,所以想「取第 n 個元素」,直接下標往往會拿到意料之外的結果。下面這個函式把非元素節點過濾掉,同時支援兩種呼叫形式。目前版本只支援以標籤名稱挑選元素,功能仍有擴充空間。
<ul id="list"> <li>1<button>a</button></li> <li>2<button>b</button><button>o</button></li> <p>test</p> <li>3<button>c</button></li> <li>4<button>d</button></li> <li>5<button>e</button></li> </ul>
/**
* @param parent 父節點
* @param ele 要選取的元素標籤
* @param num 第幾個元素
* @return {*}
*/
function nth(parent, ele, num){
var _ele = Array.prototype.slice.call(parent.childNodes), eleArray = [];
// 把子節點轉成陣列;eleArray 只用來存元素節點
for(var i = 0, len = _ele.length; i < len; i++){
if(_ele[i].nodeType == 1){
eleArray.push(_ele[i]); // 過濾掉非元素節點
}
}
if(arguments.length === 2){
// 只傳兩個參數時:第二個參數是字串則取出該標籤的所有元素
// 第二個參數是數字則取出父節點下第幾個元素節點
if(typeof arguments[1] === "string"){
return Array.prototype.slice.call(parent.getElementsByTagName(arguments[1]));
}else if(typeof arguments[1] === "number"){
return eleArray[arguments[1]];
}
}else{
// 參數齊全時回傳指定標籤下的第幾個元素,索引從 0 開始
return Array.prototype.slice.call(parent.getElementsByTagName(ele))[num];
}
}
var list = document.getElementById("list");
console.log(nth(list, "li", 2).innerHTML); // 第三個 li
console.log(nth(list, "button", 3).innerHTML); // 第四個 button
console.log(nth(nth(list, "li", 1), "button", 1).innerHTML); // 第二個 li 下的第二個 button
console.log(nth(nth(list, "li", 1), "button")); // 第二個 li 下的所有 button
console.log(nth(list, 2)); // 第二個元素節點
一是支援 CSS 選擇器:把 getElementsByTagName 換成 querySelectorAll,呼叫方式會直覺很多;二是索引的邊界處理,目前傳入超出範圍的數字會得到 undefined,若要更友善可回傳 null;三是效能,每次呼叫都做陣列轉換,在大量操作時可以考慮改用 while 迴圈直接走訪 firstElementChild / nextElementSibling。