You are here: Reference > JavaScript > client-side > HTML DOM > methods > createElement (document, XMLDocument)

createElement method (document, XMLDocument)

Browser support:
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.

Syntax:

object.createElement (tagName);
You can find the related objects in the Supported by objects section below.

Parameters:

tagName
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? yes no

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? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content