Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

info on javascript document.createElement()

How do I create the following markup using JavaScript's document.createElement function?

<input type="hidden" value="" id="" />
like image 202
Hulk Avatar asked Jan 18 '10 14:01

Hulk


People also ask

What is document createElement in JavaScript?

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.

What does createElement () do?

In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.

What does document createElement (' a ') return?

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.

What is document in JavaScript?

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.


2 Answers

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.

like image 59
Asaph Avatar answered Sep 19 '22 16:09

Asaph


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);
like image 32
Alf Eaton Avatar answered Sep 20 '22 16:09

Alf Eaton