Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Access elements from a function

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");
  });
 });

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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?

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!