Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu October 10, 2022 . #Button . #HowTo

How to create a button in JavaScript dynamically

Our topic for today is How do you create a button using JavaScript?

Example
<script type="text/javascript">
 const btn = document.createElement("BUTTON");
 btn.innerHTML = "I am a button";
 document.body.appendChild(btn);
</script>
Try it Yourself »

Follow the 3 steps to make a button with javascript.

  1. To create a button in javascript, you need to call the document.createElement("BUTTON") method and assign the created element to a variable . e.g.
    const btn = document.createElement("BUTTON");
  2. Then assign some text to the button with btn.innerHTML property. e.g.
    btn.innerHTML= "I am a button.";
  3. Finally, append the created button to the body tag using document.body.appendChild() method.
    document.body.appendChild(btn);
You can show the created button anywhere inside the body tag using the appendChild() method.

How to show the created button inside a div element.

  1. Create a div inside the body tag with an id.
  2. Call the document.getElementById(elementID) method and assign it to a variable named demoDiv.
  3. Use demoDiv.appendChild(btn); instant of document.body.appendChild(btn);
<div id="div-container"></div>
<script type="text/javascript">
 const demoDiv = document.getElementById("div-container");
 const btn = document.createElement("BUTTON");
 btn.innerHTML = "I am a button";
 demoDiv.appendChild(btn);
</script>

You can also set the button's id, class, name attributes.

Let create a button with id attribute in javascript.

Example
<html>
 <body>
  <script type="text/javascript">
   const btn = document.createElement("BUTTON");
   btn.innerHTML = "click me";
   btn.id = "btn-id";
   btn.class = "btn-class";
   btn.type = "submit";
   btn.name = "btn-name";
   document.body.appendChild(btn);
   alert(btn.class);
 </script> 
 </body>
</html>
output
 <button id="btn-id" class="btn-class" type="submit" name="btn-name">
   click me 
 </button>

JavaScript create button with onclick attribute.

Example
<html>
 <body>
  <script type="text/javascript">
   const btn = document.createElement("BUTTON");
   btn.innerHTML = "click me";
   btn.onclick = function(){
     alert("button is clicked");
   };
   document.body.appendChild(btn);
  </script>
 </body>
</html>

Conclusion

In this article, you have learned how to create a button element using javascript dynamically. Now, you should know

[1] how to create multiple buttons in one click using javascript.

[2] How to get the value of clicked button.

save
listen
AI Answer
1 Answer
  1. Nodirbek Fayzullayev
    I tried to create a button "Stop the Test" on the multiple quiz test form.
    But something went wrong that it is not working.
    Reply Delete
    Share
Write Your Answer
loading
back
View All