Home >Web Front-end >JS Tutorial >A js function to get the nth element node_javascript skills

A js function to get the nth element node_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:37:551383browse

A function that obtains the nth element node. Currently, the element can only be obtained through html tags, and the function is not yet complete

Demo: html

<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>

js:

/**
*
* @param parent父节点
* @param ele要选取的元素标签
* @param num第几个元素
* @return {*}
*/
function nth(parent,ele,num){
var _ele=Array.prototype.slice.call(parent.childNodes),eleArray=[];
//将父节点的子节点转换成数组_ele;eleArray为只储存元素节点的数组
for(var i= 0,len=_ele.length;i<len;i++){
if(_ele[i].nodeType==1){
eleArray.push(_ele[i]);//过滤掉非元素节点
}
}
if(arguments.length===2){
//如果只传入2个参数,则如果第二个参数是数字,则选取父节点下的第几个元素
//如果第二个参数是字符串,则选取父节点下的所有参数代表的节点
if(typeof arguments[1]==="string"){
_ele=Array.prototype.slice.call(parent.getElementsByTagName(arguments[1]));
return _ele;
}else if(typeof arguments[1]==="number"){
return eleArray[arguments[1]];
}
}else{
//如果参数齐全,则返回第几个某节点,索引从0开始
_ele=Array.prototype.slice.call(parent.getElementsByTagName(ele));
return _ele[num];
}
}
/*
测试
*/
var list=document.getElementById("list");
console.log(nth(list,"li",2).innerHTML);//选取第三个li元素
console.log(nth(list,"button",3).innerHTML)//选取第四个按钮
console.log(nth(nth(list,"li",1),"button",1).innerHTML);//选取第二个li下的第二个按钮
console.log(nth(nth(list,"li",1),"button"));//选取第二个li下的所有按钮
console.log(nth(list,2));//选取第二个元素
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn