<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?
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('...', () => {
// ...
})
}
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>
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>