javascript - How to check if event target is contained within an element? - Stack Overflow

I am trying to apply event delegation and so I want to update the text when I click within the li eleme

I am trying to apply event delegation and so I want to update the text when I click within the li element but when I click inside a element, it won't fire. I don't want to attach the event listener directly to li as the list can be updated and there can be any element type within li.

const menu = document.querySelector('.menu');
const textField = document.querySelector('p');

menu.addEventListener('click', e => {
  if (e.target.matches('li')) {
    textField.textContent = e.target.textContent;
  }
});
li {
  padding: 1em;
  border: 1px solid red;
}

a {
  border: 1px solid blue;
}
<div class="menu">
  <ul>
    <li><a>Home</a></li>
    <li><a>Gallery</a></li>
    <li><a>About us</a></li>
  </ul>

  <p></p>
</div>

I am trying to apply event delegation and so I want to update the text when I click within the li element but when I click inside a element, it won't fire. I don't want to attach the event listener directly to li as the list can be updated and there can be any element type within li.

const menu = document.querySelector('.menu');
const textField = document.querySelector('p');

menu.addEventListener('click', e => {
  if (e.target.matches('li')) {
    textField.textContent = e.target.textContent;
  }
});
li {
  padding: 1em;
  border: 1px solid red;
}

a {
  border: 1px solid blue;
}
<div class="menu">
  <ul>
    <li><a>Home</a></li>
    <li><a>Gallery</a></li>
    <li><a>About us</a></li>
  </ul>

  <p></p>
</div>

Share Improve this question asked Aug 23, 2021 at 15:33 noob_codernoob_coder 551 gold badge2 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

If you want the li and not the anchor or any other child element, use closest

const li = e.target.closest("li");
if (li) { /* do whatever */ }

You can make use of the bubbling effect by attaching a click event listener to the parent list, ul.

const menu = document.querySelector('.menu');
const ul = menu.querySelector('ul');
const textField = document.querySelector('p');

ul.addEventListener('click', e => {
  if(e.target != ul) textField.textContent = e.target.textContent;
});
li {
  padding: 1em;
  border: 1px solid red;
}

a {
  border: 1px solid blue;
}
<div class="menu">
  <ul>
    <li><a>Home</a></li>
    <li><a>Gallery</a></li>
    <li><a>About us</a></li>
  </ul>

  <p></p>
</div>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744225721a4563995.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信