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!".
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-01-15 11:00:00 +0000
Seen: 8 times
Last updated: Aug 09 '21
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
What is the process for generating a dynamic subdomain/URL using vue.js?
How can I create a transition on click using CSS without the need for JavaScript?
How can the style of the loader be modified while the form submission is being processed?
I'm attempting to develop a Javascript-based comments section for my website.
What are some feasible methods to enable MIDI file playback on a web browser?