Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array from filter click

I have a list of elements, I want to get on click only the one that I clicked on.I tried to do it this way

const menuItems = document.querySelectorAll(".Account-navigation-item-link");

menuItems.forEach((item) => {
  item.addEventListener("click", () => {
    let its = Array.from(menuItems)
      .filter((i) => i.click)
console.log(its)




  });
});
  <ul class="Account-navigation">
   
  <a
        href="#"
        class="Account-navigation-item-link Account-navigation-item-link-active"
        >Мои данные</a
      >
  <a
        href="#"
        class="Account-navigation-item-link"
        >Схемы лечения</a
      >
   
   
      <a
        href="/logout"
        class="Account-navigation-item-link"
        >Выйти</a
   
  </ul>

But now I get all elements

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use event.target or event.currentTarget to get the element that is clicked. The difference is that event.currentTarget will always return the element which we have bound the click event listener to, while event.target may refer to descendants inside the clicked element.

In your case, since the <a> tags have no descendants, event.target or event.currentTarget will always yield the same element, and it shouldn’t matter which one you use.

const menuItems = document.querySelectorAll(".Account-navigation-item-link");

menuItems.forEach((item) => {
  item.addEventListener("click", (e) => {
    console.log(e.currentTarget);
  });
});
<ul class="Account-navigation">
   
  <a
        href="#"
        class="Account-navigation-item-link Account-navigation-item-link-active"
        >Мои данные</a
      >
  <a
        href="#"
        class="Account-navigation-item-link"
        >Схемы лечения</a
      >
   
   
      <a
        href="/logout"
        class="Account-navigation-item-link"
        >Выйти</a
   
  </ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading