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

125
Views
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 answers
Answer question

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 Report

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 Report

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 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!