Is it possible to get element's numerical index in its parent node without looping?

前端 未结 7 1457
攒了一身酷
攒了一身酷 2020-11-30 07:21

Normally I\'m doing it this way:

for(i=0;i
7条回答
  •  无人及你
    2020-11-30 07:43

    function getChildNumber(node) {
      return Array.prototype.indexOf.call(node.parentNode.childNodes, node);
    }
    

    This seems to work in Opera 11, Firefox 4, Chromium 10. Other browsers untested. It will throw TypeError if node has no parent (add a check for node.parentNode !== undefined if you care about that case).

    Of course, Array.prototype.indexOf does still loop, just within the function call. It's impossible to do this without looping.

提交回复
热议问题