To add an EventListener to every div created by JavaScript, you can use a loop to iterate through all the div elements and add the EventListener using the addEventListener method. Here is an example:
// Create a new div element dynamically
let newDiv = document.createElement('div');
// Set the class name of the div
newDiv.className = 'myDivClass';
// Append the div to the document body
document.body.appendChild(newDiv);
// Get all the div elements with class name "myDivClass"
let divs = document.querySelectorAll('.myDivClass');
// Loop through all the div elements and add an EventListener
divs.forEach(function(div) {
div.addEventListener('click', function() {
console.log('Div clicked!');
});
});
This code creates a new div element with class name "myDivClass" and appends it to the document body. It then uses the querySelectorAll method to get all the div elements with that class name and loops through them using the forEach method to add a click EventListener to each of them. When a div is clicked, the console will log "Div clicked!".
Asked: 2023-01-15 11:00:00 +0000
Seen: 7 times
Last updated: Aug 09 '21