
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.
- Use the createElement() method and set in a variable.
let newBtn = document.createElement('button');
- 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. - 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
How to create a button with id in JavaScript
0
To create a button, we have to use the createElement() method. In this article, I will exp…
asked
Apu
0 answers
2915
To create a button, we have to use the createElement() method. In this article, I will exp…
Answer Link
answered
Apu