When utilizing the querySelectorAll method, it will result in a NodeList. The NodeList comes with an item method.
Modification
let mySpan = document.querySelector('span')[999];
should be changed to
let mySpan = document.querySelectorAll('span').item(999);
Using DevTools
Although there may be a simpler approach, one way is to inspect the desired element, choose "Copy selector" from the context menu, and then paste the selector. This process will provide you with the nth-child
information.
https://i.sstatic.net/e41U3.png
Enhancing Elements
You have the option of selecting the elements, iterating through them, and assigning an attribute to each one with its index within the NodeList. The following script can be executed in the DevTools console. Inspecting an element will reveal a data-idx
attribute like this:
<span data-idx="3">foo</span>
[].forEach.call(document.querySelectorAll('#js_by span span'), (span, idx) => span.dataset.idx = idx);
<div id="js_by">
<div>
<ul>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
</ul>
</div>
</div>
Alternative HTML Solution
An alternative method involves converting your unordered list into an ordered list, which will display the number of elements. Remember that while a NodeList
follows a zero-based index, an ordered list starts counting at one.
[].forEach.call(document.querySelectorAll('#js_by ul'), ul => {
let ol = document.createElement('ol');
let parent = ul.parentElement;
ol.innerHTML = ul.innerHTML;
parent.removeChild(ul);
parent.appendChild(ol);
});
<div id="js_by">
<div>
<ul>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
<li>
<a href="#"><span><span>foo</span></span></a>
</li>
</ul>
</div>
</div>