Home > Enterprise >  Array from filter click
Array from filter click

Time:01-10

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 >
   
  <a
        href="#"
        
        >Мои данные</a
      >
  <a
        href="#"
        
        >Схемы лечения</a
      >
   
   
      <a
        href="/logout"
        
        >Выйти</a
   
  </ul>

But now I get all elements

enter image description here

CodePudding user response:

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 >
   
  <a
        href="#"
        
        >Мои данные</a
      >
  <a
        href="#"
        
        >Схемы лечения</a
      >
   
   
      <a
        href="/logout"
        
        >Выйти</a
   
  </ul>

CodePudding user response:

const menuItems = document.querySelectorAll(".Account-navigation-item-link");
let isClick = false;
menuItems.forEach((item) => {
  item.addEventListener("click", () => {  
      let its = Array.from(menuItems).filter(function(e) {
            return event.currentTarget == e;
      })
      console.log(its);
    
  });
});

You should try this.

  •  Tags:  
  • Related