Ask Your Question
3

What is the method for adding an EventListener to every div created by JavaScript?

asked 2023-01-15 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-08-09 03:00:00 +0000

woof gravatar image

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

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-01-15 11:00:00 +0000

Seen: 7 times

Last updated: Aug 09 '21