You are here: Reference > JavaScript > client-side > HTML DOM > methods > createElement (document, XMLDocument)
createElement method (document, XMLDocument)
Creates an element with the specified tag name.
After the element is created, use the appendChild or insertBefore method to insert it into a document.
- If you want to create a CommentNode or TextNode, use the createComment and createTextNode methods.
- The following methods can also be used to create table related elements: createCaption, createTFoot, createTHead, insertCell, insertRow.
- If you want to create an image element, the var img = new Image (width, height); formula can also be used, where the width and height parameters specify initial values for the width and height properties of the image.
- If you want to create an option element, the var option = new Option (text, value); formula can also be used, where the text and value parameters specify initial values for the text and value properties of the option.
- To create an element with namespace prefix, use the createElementNS method instead.
Syntax:
You can find the related objects in the Supported by objects section below.
Parameters:
Required. String that specifies the tag name of the element to be created. The nodeName property of the created element is set to this value. |
Return value:
Returns the newly created element.
Example HTML code 1:
This example illustrates the use of the createElement method.
|
||||
<head> <script type="text/javascript"> function AddAChild () { var newElem = document.createElement ("div"); newElem.innerHTML = "sample text"; newElem.style.color = "red"; var container = document.getElementById ("container"); container.appendChild (newElem); } </script> </head> <body> <button onclick='AddAChild ();'>Add a div element to the container!</button> <div id="container"></div> </body> |
||||
|
||||
Did you find this example helpful?
|
Example HTML code 2:
This example uses the innerHTML property to implement the same functionality as the previous example:
|
||||
<head> <script type="text/javascript"> function AddAChild () { var container = document.getElementById ("container"); container.innerHTML += "<div style='color:red'>sample text</div>"; } </script> </head> <body> <button onclick='AddAChild ();'>Add a div element to the container!</button> <div id="container"></div> </body> |
||||
|
||||
Did you find this example helpful?
|
Supported by objects:
Related pages:
External links:
User Contributed Comments