I'm trying to find the index of my list item by id in Javascript. For example I have list of 5 items and given an element I want to figure out which position it is in the list. Below is the code that I hope to build on.
It's using an onclick handler to find the element, which is working, I then just need to figure out the position of the element in the list 'squareList' in some way.
window.onload=function(){
function getEventTarget(e){
var e=e || window.event;
return e.target || e.srcElement;
}
function selectFunction(e){
var target=getEventTarget(e);
alert(target.id);
}
var squareList=document.getElementById('squareList');
squareList.onclick=function(e){
selectFunction(e);
}
}
To get the index, you can do:
Array.prototype.indexOf.call(squareList.childNodes, target)
And with jQuery, as you're already using cross-browser workarounds:
$(document).ready(function() {
$('#squareList li').click(function() {
var index = $(this).index();
})
});
I have another solution and would like to share
function getEventTarget(e) {
e = e || window.event;
return e.target || e.srcElement;
}
let ul = document.getElementById('squareList');
ul.onclick = function(event) {
let target = getEventTarget(event);
let li = target.closest('li'); // get reference by using closest
let nodes = Array.from( li.closest('ul').children ); // get array
let index = nodes.indexOf( li );
alert(index);
};
You can verify here
Reference: closest
With es6 and findIndex
Transform the ul node list into an array: [...UL_ELEMENT.children]
then use findIndex
to check for the element you are looking for.
const index = [...UL_ELEMENT.childNodes].findIndex(item => item === LI_ELEMENT)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With