Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda