Js基礎學習之 -- DOM兼容 根據標籤、類名獲取節點函數封裝
1. 作用:所有類選擇器名爲cName的標籤
參數:類選擇器的名(class名)返回值:所有類選擇器名爲cName的標籤
function getClass(cName){
var arr = [];
var allTag = document.getElementsByTagName("*");
for(var i = 0; i < allTag.length; i++){
if(allTag[i].className == cName){
arr.push(allTag[i]);
}
}
return arr;
}
測試:console.log(getClass("Name"));
2. 作用:返回過濾空白文本節點和註釋節點後的元素節點集合
參數1:父級節點
返回值:元素節點集合
<pre name="code" class="javascript"><pre name="code" class="javascript">function getChildNodes(element){
var arr = [];
var eList = element.childNodes;
for(var i = 0;i < eList.length;i++){
if(eList[i].nodeType == 1){//過濾空白節點
arr.push(eList[i]);
}
}
return arr;
}
調用示例:
var obj = getChildNodes(父級節點對象);
console.log(obj);
3. 作用:獲取最後一個孩子節點
參數1: 父級元素對象
返回值:返回此對象的最後一個非空孩子節點
<pre name="code" class="javascript"> function getlastChild(element){
var lChild = null;
var allsubobj = element.childNodes;
for(var i=allsubobj.length-1;i >= 0;i--)
if(allsubobj[i].nodeType == 1){//過濾空白節點
lChild = allsubobj[i];
break;
}
return lChild;
4. 作用:獲取第一個孩子節點
參數1: 父級元素對象
返回值:返回此對象的第一個非空孩子節點
<pre name="code" class="javascript">function getfirstChild(element){
var fChild = null;
var eList = element.childNodes;
for(var i = 0;i < eList.length;i++)
if(eList[i].nodeType == 1){//過濾空白節點
fChild = eList[i];
break;
}
return fChild;
}
5. 作用:獲取下一個非空節點
參數1: 元素對象
返回值:返回此對象的下一個非空節點
<pre name="code" class="javascript">function getNextSibling(element){
var obj = element.nextSibling;
while(obj != null && obj.nodeType != 1){
obj = obj.nextSibling;
}
return obj;
}
6. 作用:獲取上一個非空節點
參數1: 元素對象
返回值:返回此對象的上一個非空節點
<pre name="code" class="javascript">function getPreviousSibling(element){
var obj = element.previousSibling;
while(obj != null && obj.nodeType != 1){
obj = obj.previousSibling;
}
return obj;
}