How do I create the following markup using JavaScript's document.createElement
function?
<input type="hidden" value="" id="" />
The document. createElement() is used to dynamically create an HTML element node with the specified name via JavaScript. This method takes the name of the element as the parameter and creates that element node.
In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
The nodeName of the created element is initialized to the elementName value. The document. createElement() returns the newly created element. Example 1: This example illustrates how to create a <p> element.
The document object represents your web page. If you want to access any element in an HTML page, you always start with accessing the document object. Below are some examples of how you can use the document object to access and manipulate HTML.
Here is some code to create your input box:
var element = document.createElement('input');
element.type = 'hidden';
element.value = '';
element.id = '';
To add it to a <form>
with id="myform"
you could do this:
var myform = document.getElementById('myform');
myform.appendChild(element);
FYI: Your <input>
doesn't have a name
attribute. If you're planning on submitting it as part of a form and processing it on the server side, you should probably include one.
Using DOM methods:
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("value", "");
input.setAttribute("id", "");
document.getElementById("the-form-id").appendChild(input);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With