How to create a form dynamically via JavaScript?

Sometimes, we want to create a form dynamically via JavaScript.

In this article, we’ll look at how to create a form dynamically via JavaScript.

How to create a form dynamically via JavaScript?

To create a form dynamically via JavaScript, we use the createElement method.

For instance, we write

const f = document.createElement("form");
f.setAttribute("method", "post");
f.setAttribute("action", "submit.php");

const i = document.createElement("input");
i.setAttribute("type", "text");
i.setAttribute("name", "username");

const s = document.createElement("input");
s.setAttribute("type", "submit");
s.setAttribute("value", "Submit");

f.appendChild(i);
f.appendChild(s);

document.body.appendChild(f);

to call createElement with 'form' to create a form element.

Then we set its attributes by calling setAttribute with the attribute name and value.

Next, we call createElement with 'input' to create input elements.

Then we call f.appendChild to append the inputs to the form as its children.

Finally, we call document.body.appendChild with f to append the form as the body’s last child.

Conclusion

To create a form dynamically via JavaScript, we use the createElement method.