一个获取第n个元素节点的js函数

时间:2021-05-25

一个获取第n个元素节点的函数,现在只能通过html标签获取元素,功能还不完善

演示: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));//选取第二个元素

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章