Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu August 25, 2022 › #Button #dynamically

How to create a button with id in JavaScript

To create a button, we have to use the createElement() method.

In this article, I will explain two different methods of dynamically creating a button element with id in JavaScript

Using Javascript Id property.

For creating a button, we use the createElement() method. To add an unique id to that button, we will use the id property.

  1. Use the createElement() method and set in a variable.
    let newBtn = document.createElement('button');
  2. Use the id property to set an id to that button.
    let newBtn = document.createElement('button');
    newBtn.innerHTML = "My new button";
    newBtn.id = "button-id";
    I have added some text to the button using the innerHTML property so that the button can be visible.
  3. Now append the button to the body element as a child.
    let newBtn = document.createElement('button');
    newBtn.innerHTML = "My new button";
    newBtn.id = "button-id";
    document.body.appendChild(newBtn);
Demo : create button's id using id property
<script>
 let newBtn = document.createElement('button');
 newBtn.innerHTML = "My new button";
 newBtn.id = "button-id";
 document.body.appendChild(newBtn);
</script>
Try it Yourself »

Using the setAttribute method.

Demo : using setAttribute() method
<script>
 let newBtn = document.createElement('button');
 newBtn.innerHTML = "My new button";
 newBtn.setAttribute("id","button-id");
 document.body.appendChild(newBtn);
</script>
Try it Yourself »
save
listen
AI Answer
Write Your Answer
loading
back
View All