Finding DOM node index

前端 未结 7 1988
死守一世寂寞
死守一世寂寞 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:58

    A little shorter, expects the element to be in elem, returns k.

    for (var k=0,e=elem; e = e.previousSibling; ++k);
    

    After a comment from Justin Dearing I reviewed my answer and added the following:

    Or if you prefer "while":

    var k=0, e=elem;
    while (e = e.previousSibling) { ++k;}
    

    The original question was how to find the index of an existing DOM element. Both of my examples above in this answer expects elem to be an DOM element and that the element still exists in the DOM. They will fail if you give them an null object or an object that don't have previousSibling. A more fool-proof way would be something like this:

    var k=-1, e=elem;
    while (e) {
        if ( "previousSibling" in e ) {
            e = e.previousSibling;
            k = k + 1;
        } else {
            k= -1;
            break;
        }
    }   
    

    If e is null or if previousSibling is missing in one of the objects, k is -1.

提交回复
热议问题