1

I wanted to to know is there a way that I can access an element that was created from a function. I am trying to set a click event for every element created but I cant get it to work. Thanks in Advance

function createDuck() {
  let newDuck = document.createElement("div");
  newDuck.classList.add("duck");
  randomPosition(newDuck);
  body.appendChild(newDuck);
  return newDuck;
};

const ducks = document.querySelectorAll("duck");
 
ducks.forEach(function (item) {  
  item.addEventListener("click", () => {
    item.classList.add("shot");
  });
 });
Sercan
  • 4,739
  • 3
  • 17
  • 36
ajthacode
  • 17
  • 2

2 Answers2

1

The following solution adds an event listener to the dynamically created <div> element with the class style .duck applied.

let body = document.getElementsByTagName("body")[0];
let button = document.getElementById('create');
let ducks = document.querySelectorAll("duck");
let counter = 0;

/* This function is used to create a new item. */
function createDuck() {
  let newDuck = document.createElement("div");
  newDuck.innerHTML = counter++;
  newDuck.classList.add("duck");
  body.appendChild(newDuck);
  return newDuck;
};

/* This method checks if the element applies a class style. */
function hasClass(elem, className) {
  return elem.className.split(' ').indexOf(className) > -1;
}

/* This event listener triggers new item creation. */
button.addEventListener('click', function() {
  createDuck();
});

/* The following item adds an event listener to the dynamically created item. */
document.addEventListener('click', function (e) {
  if(hasClass(e.target, 'duck')) {
    e.target.classList.add('shot');
  }
}, false);
.duck {
  color: red;
  border: 1px solid blue;
  margin-top: 10px;
  cursor: pointer;
}

.shot {
  background-color: yellow;
}
<body>
  <button id="create">Create</button>  
</body>

1 - Event binding on dynamically created elements?

Sercan
  • 4,739
  • 3
  • 17
  • 36
0

You call "createDuck()" nowhere. After calling it, element Will be available.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Rodion
  • 27
  • 5