A function to get the nth element node, now only gets the element through the first entry HTML tag, the function is not perfect
Demo: HTML
<ulID= "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:
1 /**2 *3 * @param parent Parents node4 * @param ele the element label to select5 * Number of elements @param num6 * @return {*}7 */8 functionNth (parent,ele,num) {9 var_ele=array.prototype.slice.call (parent.childnodes), elearray=[];Ten //converts a child node of a parent node to an array of _ele;elearray as a storage element node only One for(varI= 0,len=_ele.length;i<len;i++){ A if(_ele[i].nodetype==1){ -Elearray.push (_ele[i]);//filter out non-element nodes - } the } - if(arguments.length===2){ - //If only 2 parameters are passed in, if the second argument is a number, select the first element under the parent node - //If the second argument is a string, select the node represented by all parameters under the parent node + if(typeofarguments[1]=== "string"){ -_ele=array.prototype.slice.call (Parent.getelementsbytagname (arguments[1])); + return_ele; A}Else if(typeofarguments[1]=== "Number"){ at returnElearray[arguments[1]]; - } -}Else{ - //If the parameter is complete, the first node is returned, and the index starts at 0. -_ele=Array.prototype.slice.call (Parent.getelementsbytagname (ele)); - return_ele[num]; in } - } to /* + Test - */ the varList=document.getelementbyid ("list"); *Console.log (Nth (list, "Li", 2). InnerHTML);//Select a third LI element $Console.log (Nth (List, "button", 3). InnerHTML)//Select the fourth buttonPanax NotoginsengConsole.log (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 buttons under the second Li theConsole.log (nth (list,2));//Pick a second element
JS gets the nth element node