Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the index of the li clicked in javascript

Just using javascript, need to get the index of the li that's clicked with the following listener:

var ulList = document.getElementById('todo-list');

ulList.addEventListener('click', function(e){
   if( e.target.nodeName == "BUTTON") {

   //IS THERE A WAY INSIDE HERE TO GET THE INDEX OF THE li clicked
       e.target.parentNode.remove(); 
   } 
});

each li looks like:

<li>
   <input type="checkbox" value="1" name="todo[]">
   <span class="centerSpan" style="text-decoration: none;">abc</span>
   <button class="rightButton">X</button>
</li>
like image 284
DCR Avatar asked Dec 06 '25 04:12

DCR


1 Answers

From the target (button, in this case) call closest() to get a reference to your li element

var li = e.target.closest('li');

Then get an array reference of your UL's children by using Array.from() and passing in the children HTMLCollection

var nodes = Array.from( ulList.children );
//or if you want to not depend on externally defined variables
var nodes = Array.from( li.closest('ul').children );

Finally call indexOf() to get the index

var index = nodes.indexOf( li );

If wanting to support old browsers will need to polyfill for methods like Array.from()

like image 173
Patrick Evans Avatar answered Dec 07 '25 20:12

Patrick Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!