咱们常常经过document.getElementById 方法来获取到一个元素,这个时候咱们常常须要有一个需求,那就是如何判断这个元素在父元素中的位置。html
包含文本和注释节点
原生JS有一个常见的小技巧那就是经过元素的previousSibling 属性,额外须要注意的是该属性会遍历text节点,即回车键。this
从零开始咱们能够这样的代码获取到一个元素属于父元素的第几个子元素。.net
var child = this; while( (child = child.previousSibling) != null ) i++;
案例代码以下:prototype
Html:code
<ul id="ul"><li>123</li><li id="a">a</li><li>b</li><li>c</li></ul>
JS:htm
var child = document.getElementById("a"); var i = 0; while((child = child.previousSibling) != null) i++; console.log(i) //console 1
经过循环遍历previousSibling 属性是否为null这个小技巧,就能够获取到当前元素在父元素中的位置了。ip
不包含文本节点和注释节点
实现代码以下:get
var child = document.getElementById("a"); var parent = child.parentNode; var index = Array.prototype.indexOf.call(parent,child); console.log(index)//1
原文连接:https://www.pipipi.net/code/9...pip