第一种
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body><ul id="ul"><li id="item1">item1</li><li id="item2">item2</li><li id="item3">item3</li><li id="item4">item4</li><li id="item5">item5</li><li id="item6">item6</li><li id="item7">item7</li><li id="item8">item8</li><li id="item9">item9</li><li id="item10">item10</li></ul><script>var oUl=document.getElementById('ul');var lis= oUl.firstElementChild;//console.log(lis);var item1=document.getElementById('item1');var item2=document.getElementById('item2');var item3=document.getElementById('item3');var item4=document.getElementById('item4');var item5=document.getElementById('item5');var item6=document.getElementById('item6');var item7=document.getElementById('item7');var item8=document.getElementById('item8');var item9=document.getElementById('item9');var item10=document.getElementById('item10');function getIndex(curEle){var ary=[];var pre=curEle.previousSibling;while(pre){if(pre.nodeType===1){ary.push(pre);pre=pre.previousSibling;}else{pre=pre.previousSibling; }}return ary.length;}console.log(getIndex(item2))</script></body></html>复制代码
第二种方法
// 获取当前元素在兄弟节点中的索引console.log(getIndex(lis));function getIndex(curEle) {var arr = [],i = 1;arr[0] = curEle;var temp = curEle.previousSibling;while(temp){if (temp.nodeType === 1){arr[i] = temp;i++;}temp = temp.previousSibling;}arr = arr.reverse();return arr.length-1+1;}})()复制代码
如果觉得《获取当前元素在兄弟元素节点中的索引》对你有帮助,请点赞、收藏,并留下你的观点哦!