Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda