In JavaScript è possibile reperire anche l'indice numerico di un dato elemento.
La soluzione è la seguente:
'use strict';
const index = (element, selector) => {
if(!element || element === null) {
return 0;
}
if(typeof selector !== 'string' || selector.length === 0) {
return 0;
}
let i = 0;
while ((element = element.previousElementSibling) !== null) {
if (!selector || element.matches(selector)) {
i++;
}
}
return i;
};