Finding DOM node index

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

    As with the original poster, I was trying to

    find the index of a given DOM node

    but one that I had just use a click handler on, and only in relation to its siblings. I couldn't end up getting the above to work (because of noobness undoubtably, i tried subbing in 'this' for elem but it didn't work).

    My solution was to use jquery and use:

    var index = $(this).parent().children().index(this);
    

    It works without having to specify the type of the element ie:'h1' or an id etc.

提交回复
热议问题