admin管理员组

文章数量:1303505

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>

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>
Share Improve this question asked Feb 25, 2018 at 19:31 DCRDCR 15.7k13 gold badges60 silver badges128 bronze badges 1
  • If you explain why we can probably tell you a better way to do what you need. – Reinstate Monica Cellio Commented Feb 25, 2018 at 19:49
Add a ment  | 

1 Answer 1

Reset to default 9

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

本文标签: html listshow to get the index of the li clicked in javascriptStack Overflow