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

135
Views
Loop array into button onclick event

I have this array and want to loop into buttons. The first cell will be in onclick event, the second will be in innerHTML. And append these buttons to div

The array:

rows = [
  [fun1(), 'innerhtml'],
  [fun2(), 'innerhtml'],
  [fun3(), 'innerhtml'],
];
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This will get you working as you would expect.

const fun1 = () => alert("Hello function 1");
const fun2 = () => alert("Hello function 2");
const fun3 = () => alert("Hello function 3");

const rows = [
  [fun1, 'innerhtml'],
  [fun2, 'innerhtml'],
  [fun3, 'innerhtml'],
];

const myDiv = document.getElementById('myDiv');

rows.forEach(row => {
    // Create button
    const button = document.createElement('button');

    // Apply onclick event
    button.onclick = row[0];
    button.innerHTML = row[1];

    // Append to div
    myDiv.appendChild(button);
})

const fun1 = () => alert("Hello function 1");
const fun2 = () => alert("Hello function 2");
const fun3 = () => alert("Hello function 3");

const rows = [
  [fun1, 'innerhtml'],
  [fun2, 'innerhtml'],
  [fun3, 'innerhtml'],
];

const myDiv = document.getElementById('myDiv');

rows.forEach(row => {
    // Create button
    const button = document.createElement('button');

    // Apply onclick event
    button.onclick = row[0];
    button.innerHTML = row[1];

    // Append to div
    myDiv.appendChild(button);
})
<div id="myDiv"></div>

The comments should explain what is happening throughout my code.

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!