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.
- 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");
- Then assign some text to the button with btn.innerHTML property. e.g.
btn.innerHTML= "I am a button.";
- 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.
- Create a div inside the body tag with an id.
- Call the document.getElementById(elementID) method and assign it to a variable named demoDiv.
- 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
How to create a button in JavaScript dynamically
1
Our topic for today is How do you create a button using JavaScript? Example < script type …
asked
Apu
1 answers
2915
Our topic for today is How do you create a button using JavaScript? Example < script type …
Answer Link
answered
Apu
But something went wrong that it is not working.