0

I need some help, I want to basically do this for dynamically created elements (elements that were created after page loading), I cant figure it out on my own

for (i=0;i<classname.length; i++){
    classname[i].onclick = function(){
    this.style.background = "red";
    };
}; 
or
 classname.forEach(element => {
        element.addEventListener("click", function(){
    
    })
});
  • Can you share the code when the elements are created? – Keimeno Mar 02 '21 at 21:09
  • Does this answer your question? [What is DOM Event delegation?](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – evolutionxbox Mar 02 '21 at 21:09
  • Does this answer your question? [add event listener on elements created dynamically](https://stackoverflow.com/questions/14258787/add-event-listener-on-elements-created-dynamically) – Dominik Mar 02 '21 at 21:10
  • 1
    Does this answer your question? [Attach event to dynamic elements in javascript](https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript) – Marcos Alexandre Mar 02 '21 at 21:11

3 Answers3

0

A general solution for this is to make use of event bubbling. Meaning you add an event listener to the body and check if the targets className includes the className you're looking for.

document.body.addEventListener('click', doStuff);
function doStuff({target}) {
  if (target.classList.contains(YOUR_CLASS_NAME) {
    // handle event here
  }
}
Keimeno
  • 1,893
  • 6
  • 22
0

The solution depends on how you create the html objects.

but in genreal:

let newHTMLElement = document.createElement('div')
newHTMLElement.addEventListner('click', e=>{
//some code
});
Lukas
  • 26
  • 2
0

Using your technique, you can only add event listeners to elements that exist at the time you execute the loop. Instead, set up a single listener on an ancestor of the current and future elements and leverage event bubbling so that you can implement "event delegation", where you let the events bubble up to the common ancestor and handle them there.

Not only does this approach solve your problem, but it avoids a loop entirely and only sets up one event listener instead of many (saving resources).

// In this example, the <ul> always exists and will
// be the common ancestor that dynamically created
// elements will have
const list = document.querySelector("ul");

// Make some new elements upon clicking the button:
document.querySelector("button").addEventListener("click", function(){
  const bullet = document.createElement("li");
  bullet.textContent = "Dynamically Created Element (click me)";
  bullet.classList.add("bullet");
  list.appendChild(bullet);
});

list.addEventListener("click", function(event){
  // All DOM event handlers are automatically
  // passed a reference to the event object that
  // they are responding to. That object provides
  // a .target property that references the element
  // that triggered the event

  // Determine the source of the event
  if(event.target.classList.contains("bullet")){
    console.log("You clicked a dynamically created element.");
  }
});
.bullet { color:blue; pointer:cursor; }
<button>Click to add new bullet</button>

<ul></ul>
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54