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

115
Visualizações
Select the direct children of an element and apply the function to them using JavaScript
<div class='parent'>
  <div class='child'>
     <p>test</p>
  </div>
  <div class='child'>
     <p>test</p>
  </div>
 <div>

How can I select all direct div children with parent class and execute a function on them using addEventListener?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use document.querySelectorAll to get all of the divs, and then add the event listeners inside a loop.

const divs = document.querySelectorAll('.parent > .child')
for (const div of divs) {
  div.addEventListener('...', () => {
    // ...
  })
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You only need to select the child elements. For example by using querySelectorAll.

const childs = document.querySelectorAll(".parent .child");

childs.forEach(c => c.addEventListener("click", (e) => {
  alert();
}))
<p>Click of one of the tests p tags!</p>
<div class='parent'>
  <div class='child'>
     <p>test</p>
  </div>
  <div class='child'>
     <p>test</p>
  </div>
 <div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Use event delegation. Instead of adding listeners to many elements, add one to the parent and let it capture events from its child elements as they "bubble up" the DOM. The handler function can check what child element has been triggered, and then <do something> depending on that outcome.

In this example we're checking that the element that has been clicked on is a p element that is the child of an element with a .child class, and logging its text content.

const parent = document.querySelector('.parent');

parent.addEventListener('click', handleClick, false);

function handleClick(e) {
  if (e.target.matches('.child p')) {
    console.log(e.target.textContent);
  }
}
p:hover { cursor: pointer; color: red; }
<div class="parent">
  <div class="child">
    <p>Test 1 - will be logged</p>
  </div>
  <div>
    <p>Test 2 - will not be logged</p>
  </div>
  <div class="child">
    <p>Test 3 - will be logged</p>
  </div>
  <div>
    <p>Test 4 - will not be logged</p>
  </div>
</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