Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
HTML and CSS
Methods
 createElement Method
createElement Method

Creates an instance of the element for the specified tag.

Syntax

oElement = object.createElement(sTag)

Parameters

sTag Required. A String that specifies the name of an element.

Return Value

Returns a reference to the new element.

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 programmatically, except frame and iframe. The properties of these created elements are read/write and can be accessed programmatically. 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 method or the appendChild method.

You must perform a second step when you use 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, and 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. To include the NAME attribute at run time on objects created with the createElement method, use the sTag.

Use the sTag to include attributes when form elements are created that will be reset using the reset method or a BUTTON with a TYPE attribute value of reset.

Examples

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;
</SELECT>
<SELECT ID=oText onchange="fnCreate()">
<OPTION>
<OPTION VALUE="Text">Text
<OPTION VALUE="More and More Text">More and More Text
</SELECT>
<SPAN ID="oData" ></SPAN>
This feature requires Microsoft Internet Explorer 5 or later. Click the following icon to install the latest version. Then reload this page to view the sample.

You can also specify all the attributes inside the createElement method by using an HTML string for the method argument. The following example demonstrates how to dynamically create two radio buttons utilizing this technique.

<HTML>
<HEAD>
<SCRIPT>
function createRadioButton(){
    // Create radio button object with value="First Choice" and then insert 
    // this element into the document hierarchy.
    var newRadioButton = document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='First Choice'>")
    document.body.insertBefore(newRadioButton);
    // Create radio button object with value="Second Choice" and then insert 
    // this element into the document hierarchy. 
    newRadioButton = document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>")
    document.body.insertBefore(newRadioButton);
}
</SCRIPT>
</HEAD>

<BODY>
<INPUT TYPE="BUTTON" ONCLICK="createRadioButton()" VALUE="Create two Radio Buttons"><BR>

<INPUT TYPE="BUTTON" ONCLICK="alert ( document.body.outerHTML )" VALUE="Click here to see HTML">

<BODY>
</HTML>

Standards Information

This method is defined in World Wide Web Consortium (W3C) Document Object Model (DOM) Level 1 World Wide Web link.

Applies To

document, HTMLDocument Constructor

See Also

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
DO NOT USE IT to create iframes      george_5154 ... EricLaw [MSFT]   |   Edit   |   Show History

The following is an example of unhelpful text, as it doesn't explain what platforms and bugs are found. A simple test case shows that createElement('iframe') works just fine in IE7 & IE8.



Unless of course you enjoy frustration, because sooner or later you’ll be involved in a situation in which your script will work well with all browsers except Microsoft’s IE. This happens because createElement has a bug that produces defective iframes, so they behave different from those embedded in the HTML code. I found a workaround that hope to be useful to all those how create content dynamically. Since the problem is a bug in the createElement method, the solution is simply not to use createElement to create the iframe, instead create a div and then assign the innerHTML property with HTML code for the iframe, like this:

var rem = document.createElement("div")

rem.innerHTML = '<iframe style="display:none" src="about:blank" id="rpc" name="rpc"></iframe>'

document.body.appendChild(rem)

In the example above I assume you want the iframe to be hidden

Yet another BUG!      george_5154   |   Edit   |   Show History

Any reasonable programmer, not aware of this bug, would think that the most efficient way to dynamically create horizontal lines is to use createElement to create a div and then set the height of that div to 1px and the width to whatever they want. This is approach is actually correct and safe in all browsers EXCEPT on IE which seems to set the div’s height to 15px whenever you use a value under 15px. A possible workaround is to set the fontSize to 1px, however this would make the div2 pixels high, even if you ser fontSize to 0px you will still get a line which is 2 pixels high. The best way I found to workaround this BUG is to to create a CSS entry like this:

.line {border-top:black 1px solid}

and then set the div’s className to “line”.

If anyone at Microfoft reads this, please, hold on the release of IE8, remove all new features, and concentrate in making all IE7 features to work as they are supposed to, release that version as IE8, then and only then add new features you want to IE9. We do not need the bugs you have now and certially adding new ones won’t make anyone happier.


[jsudds.MSFT] Then you should be delighted to know that we've already fixed that bug in IE7. The behavior in question is a quirks mode artifact left over from the IE6 days. For backwards compatibility, you'll get the same behavior in IE7 if you forget to specify a standards-mode DOCTYPE. Please, please, please use standards mode whenever possible. It's the only reasonable way to get any semblance of control over your Web layout in any browser.

As for your example, there are two ways to create a single pixel-width line. You can either set your content height to 0 and specify one of the two borders that appear on either side of your content box, or you can set your content height to 1px and change the background color of the div.

The following code creates a pattern of alternating red and black lines. Plus, it works equally well in all major browsers, including IE7 and IE8 in standards mode.

<script>
// #1. Set background color of 1px div
var div2 = document.createElement('div');
div2.style.height = "1px";
div2.style.backgroundColor = "#f00";
document.body.appendChild(div2);





// #2. Set top border of 0px div
var div = document.createElement('div');
div.style.height = "0";
div.style.borderTop = "1px solid black";
document.body.appendChild(div);
// Alternate lines

document.body.appendChild(div2.cloneNode(false));
document.body.appendChild(div.cloneNode(false));
</script>


[george_5154] Ok, good point, you are perfectly right, I modified my code and I witness what you say is 100% correct and valid for this case. Using the “famous” DOCTYPE standard mode not only solved this problem, in fact it did correct some other problems I was experiencing. HOWEVER I must do insist, that you should make sure things work as expected in the current version before releasing a new one, because when you combine a DOCTYPE standard mode with a dynamically created table, document.body.clientWidth reports the width of the document minus the width of the scroll bar even when there is no scroll bar on the screen, in other words it becomes unreliable!. That, does not happen if I remove the DOCTYPE standard mode, and this problem only occurs with IE7.

including attributes nonconforming      yecril   |   Edit   |   Show History

Document.createElement(tagName), as defined by W3C, does not allow HTML code in tagName. This is an extension specific to Internet Explorer.

Not able to generate DIV's , LABEL's correctly... only INPUTs and A's in IE7      J1980 ... Thomas Lee   |   Edit   |   Show History

Seems to be causing problems when I'm trying to give DIV's and LABEL's the NAME attribute like the following...

//works
var o_link = document.createElement("<a name='a_name'>");

//these don't work
var o_div = document.createElement("<div name='d_name'>");
var o_label = document.createElement("<label name='l_name'>");

Appending these (div,label) to the document with appendChild, creates the element in IE as expected..BUT the NAME isn't contained in the collection when collecting all the tags with

var myDivs = document.getElementsByName('d_name');
alert(myDivs.length); //will popup 0 everytime for a test

var myAs = document.getElementsByName('a_name');
alert(myAs.length); //will popup the correct count for a test

Is this a bug or what? I'm able to do this completely fine in FF 2+ and Safari 3+ .... Are div's and labels not allowed to have NAME attributes in the DOM collection for IE version whatever???????

Thanks

[tfl - 21 05 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at 
  http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
Processing
© 2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker