varoText = document.getElementById('text');函數
var
oBox =
document.
getElementById(
'box');
/*----封裝函數,返回該元素的第n層祖先元素-----*/
/* 1.返回第幾層? parentNoded 查詢父節點
dom 節點
n 第幾層祖先
*/
function
getParent(
dom,
n){
for(
var
i=
0;
i<
n;
i++){
if(
dom.
parentNode===
null){
return
dom;
}
dom =
dom.
parentNode;
}
return
dom;
}
getParent(
oText,
2)
//那個元素開始,第幾層
/*----封裝myChildren函數,實現系統的children功能-----*/
// dom節點返回一個有dom的元素子節點組成的數組
//children功能獲得子節點的數組,因此咱們能夠遍歷每一項,把他組成數組
var
arr = [];
function
myChildren(
dom){
for(
var
i=
0;
i<
dom.
childNodes.
length;
i++){
//搜索
if(
dom.
childNodes[
i].
nodeType===
1){
//若是傳進來的是元素節點
arr.
push(
dom.
childNodes[
i])
}
}
return
arr;
}
myChildren(
oBox)
/*-----封裝hasChildren函數,判斷有沒有元素節點,要求不能使用children屬性----*/
//若是dom元素有元素子節點,就返回true,不然flase
function
hasChildren(
dom){
for(
var
i=
0;
i<
dom.
childNodes.
length;
i++){
if(
dom.
childNodes[
i].
nodeType===
1){
return
true;
}
// else{
// return false;
// }
//不能夠這樣寫,由於判斷的時候,第一個是文檔節點,nodeType爲3,
//因此會走進else中,直接flase
}
return
false;
}
hasChildren(
oText)
/*----封裝insertAfter函數,功能和insertBefore相似----*/
// 把A插入到B後面 就至關於把A插入到B的相鄰兄弟的前面
var
oDiv =
document.
createElement(
'div');
function
insertAfter(
A,
B){
//console.log(B.nextElementSibling);
B.
parentNode.
insertBefore(
A,
B.
nextElementSibling)
}
insertAfter(
oDiv,
oText)
/*----封裝remove函數,使child.removeChild()可以刪除自身----*/
function
remove(
dom){
dom.
parentNode.
removeChild(
dom)
}
//remove(oBox);
/*----封裝函數,實現元素節點內部的順序,逆序----*/
// 使用appendChild 把節點插入到父節點的最後面 循環
var
rRse =
document.
getElementById(
'res');
function
reserve(
dom){
for(
var
i=
0;
i<
dom.
children.
length-
1;
i++){
/*
* i=0 dom.children[4]-->length-1-1-i //6-1-1-0
* i=1 dom.children[3]-->length-1-1-i //6-1-1-1
* i=2 dom.children[2]
* i=3 dom.children[1]
* i=4 dom.children[0]
*/
dom.
appendChild(
dom.
children[
dom.
children.
length-
1-
1-
i])
}
}
reserve(
rRse)