Get an element's nth-child number in pure JavaScript

前端 未结 5 724
别跟我提以往
别跟我提以往 2020-12-18 20:16

I am making a function for my site where I set a data attribute which contains the nth-child number of that element.

My HTML markup:


<         


        
5条回答
  •  囚心锁ツ
    2020-12-18 20:33

    Check out this previous answer HERE.

    It uses

    var i = 0;
    while( (child = child.previousSibling) != null ) 
      i++;
    //at the end i will contain the index.
    

提交回复
热议问题