0

Suppose i have a <ul></ul> with some number of <li></li> elements. And I wonder, what is the best way to get an index of the <li> element by clicking on its child (I have buttons inside)? Under the best way, I mean the most beginner-friendly, using vanilla JS. Maybe you, guys, have a couple of ideas to share?

I need that index to remove the related element from an array later on. What I've managed to write so far seems overcomplicated, since I have to assign ids to each element I want to click on.

function removeItem(e) {
   if (e.target.classList.contains('removeBtn')) {
      controller.tasks.splice(e.target.id, 1);
      view.renderInput(controller.tasks);
   } 
}
ulEl.addEventListener('click', removeItem);
Danny Lenko
  • 45
  • 1
  • 8
  • 1
    Use [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instead of an array, that can contain an object (ex. li element) as a key. – Teemu Jan 26 '22 at 11:24
  • And you can use [`closest`](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest) to find the `li` the button is in: `const li = e.target.closest("li"); if (li.contains(e.target)) { /*...*/ }` – T.J. Crowder Jan 26 '22 at 11:25
  • When you render your array as HTML, add `data-index="0"` etc to the delete button. That way you can read the index from `this.dataset.index` –  Jan 26 '22 at 11:26

1 Answers1

1

Suppose i have a <ul></ul> with some number of <li></li> elements. And I wonder, what is the best way to get an index of the <li> element by clicking on its child (I have buttons inside)?

Just use forEach which will give you the index as well like this:

const list = document.querySelectorAll('#someList li');
const btns = document.querySelectorAll('#someList button');

btns.forEach((btn, index) => {
    btn.addEventListener('click', () => {
    console.log(index);
    console.log(list[index]);
  });
});
<ul id="someList">
  <li>A <button>Click Me</button></li>
  <li>B <button>Click Me</button></li>
  <li>C <button>Click Me</button></li>
  <li>D <button>Click Me</button></li>
</ul>
AndrewL64
  • 15,794
  • 8
  • 47
  • 79