Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  80] [ 7]  / answers: 1 / hits: 25345  / 11 Years ago, sun, august 18, 2013, 12:00:00

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);
}
}

More From » html

 Answers
18

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();
})
});

[#76299] Thursday, August 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byronkodyo

Total Points: 552
Total Questions: 87
Total Answers: 104

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;