JavaScript programmatically create HTML button tag
Last updated:31st Aug 2022
In this article, we will learn how you can programmatically create an HTML button in javascript.
Step for creating HTML button in Javascript.
- To create a button in javascript use document.createElement("Button"). it will create a button tag.
- After creating a button, now create text for the button. for creating text use document.createTextNode("Click me"). it will create "Click me" text.
- Now add the text on a button. for adding text use innerHTML.
- append the button inside the body tag. for that use appendChild() method
see the below code for understanding.
let btn = document.createElement("button");
btn.innerHTML = "Submit";
document.body.appendChild(btn);
the above code will create following HTML button.
<button>Submit</button>
This is a simple HTML button, sometimes you need a name
and type
in a button. You can easily add a name and type in the button.
see the below example for adding name, type, and id:
let btn = document.createElement("button");
btn.innerHTML = "Submit";
btn.id="buttonID"
btn.type="submit"
btn.name="formsubmit"
document.body.appendChild(btn);
above code will create following HTML button.
<button id="buttonID" type="submit" name="formsubmit">Submit</button>
Example
<!DOCTYPE html>
<html>
<body>
<p> click on "create btn" for creating HTML button </p>
<button onclick="create_b()">create btn</button>
<script>
function create_b() {
let btn = document.createElement("button");
btn.innerHTML = "Submit";
btn.id="buttonID";
btn.type="submit";
btn.name="formsubmit";
document.body.appendChild(btn);
}
</script>
</body>
</html>