Finding DOM node index

前端 未结 7 1908
死守一世寂寞
死守一世寂寞 2020-11-27 16:09

I want find the index of a given DOM node. It\'s like the inverse of doing

document.getElementById(\'id_of_element\').childNodes[K]

I want

7条回答
  •  有刺的猬
    2020-11-27 16:48

    I think the only way to do this is to loop through the parent's children until you find yourself.

    var K = -1;
    for (var i = myNode.parent.childNodes.length; i >= 0; i--)
    {
        if (myNode.parent.childNodes[i] === myNode)
        {
            K = i;
            break;
        }
    }
    
    if (K == -1)
        alert('Not found?!');
    

提交回复
热议问题