Fastest way to find the index of a child node in parent

前端 未结 9 1535
醉梦人生
醉梦人生 2020-12-13 07:06

I want to find the index of the child div that has the id \'whereami\'.

9条回答
  •  一整个雨季
    2020-12-13 07:18

    Generally speaking, a small difference in performance has a negligible effect unless the code is run in a loop. Having to run the code once instead of every time will be significantly faster.

    Do something like this once:

    var par = document.getElementById('parent');
    var childs = par.getElementsByTagName('*');
    for (var i=0, len = childs.length;i < len;i++){
      childs[i].index = i;
    }
    

    Subsequently finding the index is as easy as:

    document.getElementById('findme').index
    

    It sounds like whatever you're doing could be benefited by having a cleaner relationship between the DOM and the javascript. Consider learning Backbone.js, a small javascript MVC library which makes web applications much easier to control.

    edit: I've removed the jQuery I used. I do normally avoid using it, but there's quite a preference for it on SO, so I assumed it would end up being used anyway. Here you can see the obvious difference: http://jsperf.com/sibling-index/8

提交回复
热议问题