Creates an instance of the element object for the specified tag.
Syntax
oElement = document.createElement(sTag)
Parameters
sTag Required. String that specifies the name of an element.
Return Value
Returns an element object.
Remarks
In Microsoft® Internet Explorer 4.0, the only new elements you can create are IMG, AREA, and OPTION. As of Internet Explorer 5, you can create all elements in script, except for FRAME, IFRAME, and SELECT. In addition, the read-only properties of independently created elements are read/write. Before you use new objects, you must explicitly add them to their respective collections or to the document. To insert new elements into the current document, use the insertBefore or appendChild methods.
You must perform a second step when using createElement to create the INPUT element. The createElement method generates an input text box, because that is the default INPUT type property. To insert any other kind of INPUT element, first invoke createElement for INPUT, then set the type property to the appropriate value in the next line of code.
Attributes can be included with the sTag as long as the entire string is valid HTML. This is useful since you cannot set the NAME attribute at run time on anchor objects created with the createElement method. For example, to create an anchor with a NAME attribute, include the attribute and value when using the createElement method. You can also use the innerHTML property.
Example
This example uses the createElement method to dynamically update the contents of a Web page by adding an element selected from a drop-down list box.
<SCRIPT> function fnCreate(){ oData.innerHTML=""; var oOption=oSel.options[oSel.selectedIndex]; if(oOption.text.length>0){ var aElement=document.createElement(oOption.text); eval("aElement." + oOption.value + "='" + oText.value + "'"); if(oOption.text=="A"){ aElement.href="javascript:alert('A link.')"; } } oData.appendChild(aElement); } </SCRIPT> <SELECT ID="oSel" onchange="fnCreate()"> <OPTION VALUE="innerText">A <OPTION VALUE="value"><INPUT TYPE="button"> <INPUT TYPE="text" ID="oText" VALUE="Sample Text"> <SPAN ID="oData" ></SPAN>
Applies To
See Also