[英]Find elements position amongst its siblings
I want to have a function that tells me where the element is relative to every other element. 我想要一个函数,告诉我该元素相对于所有其他元素的位置。
function Funk(x) { var y = //how many elements are infront of it in its parent. console.log(y) }
<ul> <li onclick='Funk(this)'>1</li> <li onclick='Funk(this)'>2</li> <li onclick='Funk(this)'>3</li> <li onclick='Funk(this)'>4</li> </ul>
In this example, I want the output to be whatever number I click. 在此示例中,我希望输出为我单击的任何数字。 So if I click on the third element, it outputs 3 . 因此,如果单击第三个元素,则输出3 。
You can use parentNode
and children
to go up and down the DOM. 您可以使用parentNode
和children
来上parentNode
DOM。
function Funk(x) { var y = 0; var children = x.parentNode.children; while (children[y] !== x) y++; y++; console.log(y) }
<ul> <li onclick='Funk(this)'>1</li> <li onclick='Funk(this)'>2</li> <li onclick='Funk(this)'>3</li> <li onclick='Funk(this)'>4</li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.