createElement Method

DHTML, HTML, & CSS

createElement Method


Creates an instance of the element object for the specified tag.

Syntax

oElement = document.createElement(sTag)

Parameters

sTagRequired. 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">&lt;INPUT TYPE="button"&gt;
<INPUT TYPE="text" ID="oText" VALUE="Sample Text">
<SPAN ID="oData" ></SPAN>
This feature requires Internet Explorer 5 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

Applies To

[ Object Name ]
PlatformVersion
Win16:
Win32:
Mac:
Unix:
WinCE:
Version data is listed when the mouse hovers over a link, or the link has focus.

document

See Also

add, cloneNode, removeNode


Back to topBack to top

Did you find this topic useful? Suggestions for other topics? write us!Internet Link

© 1999 microsoft corporation. all rights reserved. terms of useInternet Link.