Finding an item reference to a DOM element

Consider a huge DOM with about 10,000 HTML elements, between them, a 1,000 span tags.

Basically no span has any identifier and all nested deep inside other objects having a very long Xpath which is not comfortable to work with.

Given all spans form an array like group, starting from 0 to 999 and we want to know what is the item reference of each unit so to select, say span 1000 we’ll do:

let mySpan = document.querySelector('span')[999];

Is there a way to know what is the item reference of that specific span element (or any other element for that matter)?

I didn’t find any way in the current releases of Firefox and Chrome, but maybe I missed it in the devtool or some tweak could be utilized for that.

I don’t think I would want to depend on working with an elements count.

But I do like using querySelector. What I usually do is go up the chain of parent nodes until I find an id, then I drill back down to the element, using class when available. It can make for some verbose selectors and it can be fragile to DOM changes, but IMHO less fragile than using element count.

Any particular reason you want / need to do it this way?

The reason is because I translated the elements Xpath:


To the following code:

document.querySelector(' #js_en > div > ul > li:nth-child(4) > a > span > span ').click()

And when I executed, the console outputted:

Cannot read property of null

Hence, the element wasn’t clicked.

So, seems I have only 2 options left: Either do it with an item reference, as I suggested, or doing it the way you suggested.

The way you suggest seems better because it’s less fragile. Can you elaborate on how it’s different than an Xpath? Especially given my Xpath didn’t work?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.