Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript find li index within ul

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);
    }
}
like image 956
Daniel Rasmuson Avatar asked Aug 18 '13 04:08

Daniel Rasmuson


3 Answers

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();
    })
});
like image 100
Blender Avatar answered Nov 19 '22 11:11

Blender


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

like image 4
Tuan Hoang Avatar answered Nov 19 '22 13:11

Tuan Hoang


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)
like image 3
ncubica Avatar answered Nov 19 '22 11:11

ncubica