
Apu
October 30, 2022 ›
#Button
›
#dynamically
❌
How to create multiple buttons dynamically in javascript
In this article, you will learn how to create multiple buttons dynamically in javascript.
To create only one button in javascript, it's easy but for creating multiple buttons dynamically in javascript, we have to use a loop for loop.
Basically, a loop repeats the same code over and over again.
Create multiple buttons dynamically in javascript.
We will create a <div> element to display the created buttons and also create a <button> element whenever the button will be clicked , a function myFunction() will be involved.
Demo : create multiple buttons in js
<div id="button-container"></div>
<button onclick="myFunction(4)">Create Button</button>
<script>
function myFunction(e){
for(let i = 0; i< e; i++){
let newBtn = document.createElement('button');
newBtn.innerText="Click me";
document.querySelector('#button-container').appendChild(newBtn);
}
}
</script>
Try it Yourself »
- Create a <div> element with an id id="button-container" where the created buttons will be displayed.
<div id="button-container"></div>
- Create a <button> element with the onclick attribute. Write down the function name inside the double quotes. Don't forget to add the opening and the closing circular brackets after the function name and also pass a number as an argument.
<button onclick="myFunction(5)">Create Button</button>
- Now , write down the myFunction inside the <script> tag.
- Inside the myFunction, add a for-loop that will repeat 5 times.
function myFunction(e){ for(let i = 0; i< e; i++){ } }
We passed a parameter e inside the function myFunction(e). The parameter e returns the value passed inside the button element. - Inside the for loop, create a button using the createElement() method. How to create a button
function myFunction(e){ for(let i = 0; i< e; i++){ let newBtn = document.createElement('button'); newBtn.innerText="Click me"; } }
- Finally, append the created buttons to the <div> element as a child.
function myFunction(e){ for(let i = 0; i< e; i++){ let newBtn = document.createElement('button'); newBtn.innerText="Click me"; document.querySelector('#button-container').appendChild(newBtn); } }
Click on the Try it Yourself » button to open the code in Editor.
Example : create multiple buttons dynamically
Try it Yourself »
save
listen
AI Answer
How to create multiple buttons dynamically in javascript
2
In this article, you will learn how to create multiple buttons dynamically in javascript. …
asked
Apu
2 answers
2915
In this article, you will learn how to create multiple buttons dynamically in javascript. …
Answer Link
answered
Apu
function createButton(btnText){
let myBtn = document.createElement('button');
myBtn.innerText = btnText;
return myBtn
}
console.log(createButton('hi'))