Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
How to check if event target is contained within an element?

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>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 */ }
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!