A js function that gets the NTH element node

  • 2020-03-30 03:50:00
  • OfStack

A function to get the NTH element node, now only through the HTML tag to get the element, function is not perfect

Presentation: the 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:



function nth(parent,ele,num){
var _ele=Array.prototype.slice.call(parent.childNodes),eleArray=[];
//Converts the children of the parent node to array _ele; EleArray is an array that stores only element nodes
for(var i= 0,len=_ele.length;i<len;i++){
if(_ele[i].nodeType==1){
eleArray.push(_ele[i]);//Filter out non-element nodes
}
}
if(arguments.length===2){
//If only two parameters are passed in, then if the second parameter is a number, which element under the parent node is selected
//If the second argument is a string, the node represented by all the arguments under the parent node is selected
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{
//If the parameters are complete, which node is returned and the index starts at 0
_ele=Array.prototype.slice.call(parent.getElementsByTagName(ele));
return _ele[num];
}
}

var list=document.getElementById("list");
console.log(nth(list,"li",2).innerHTML);//I'm going to pick the third li element
console.log(nth(list,"button",3).innerHTML)//Select the fourth button
console.log(nth(nth(list,"li",1),"button",1).innerHTML);//Select the second button under the second li
console.log(nth(nth(list,"li",1),"button"));//Select all the buttons under the second li
console.log(nth(list,2));// Select the second element 

Related articles: