A _javascript technique for acquiring the JS function of the nth element node

Source: Internet
Author: User

A function to get the nth element node, which is now only available through the HTML tag, and the function is not perfect.

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 parent node * @param ele the element label to select * @param num the first few elements * @return {*}/function Nth (parent,ele,num) {var _ele=a
Rray.prototype.slice.call (Parent.childnodes), elearray=[];
Converts a child node of a parent node to an array of _ele;elearray for only the element nodes (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 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 all the parameters under the parent node to represent the node 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 parameter is complete, return the first few nodes, the index starting from 0 _ele=array.prototype.slice.call (Parent.getelementsbytagname (ele));
];
}/* Test * * var List=document.getelementbyid ("list");
Console.log (Nth (list, "Li", 2). InnerHTML)//Select the third Li element Console.log (nth (List, button, 3). InnerHTML)//Select the fourth button Console.log (Nth (nth (list, "Li", 1), "button", 1);//Select the second button under the second Li Console.log (nth (list,Li ", 1)," button ");//Select All buttons under the second Li Console.log (nth (list,2)), or select the second element 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.