Visit Mozilla.org

DOM:document.createElement

From MDC

« Gecko DOM Reference

Contents

[edit] Summary

Creates an element with the specified tag name.

[edit] Syntax

element = document.createElement(tagName);
  • element is the created element object.
  • tagName is a string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName.

[edit] Example

This creates a new <div> and inserts it before the element with id "org_div1":

<html>
<head>
<title>||Working with elements||</title>
</head>

<script type="text/javascript">
var my_div = null;
var newDiv = null;

function addElement()
{
  // create a new div element
  // and give it some content
  newDiv = document.createElement("div");
  newDiv.innerHTML = "<h1>Hi there and greetings!</h1>";

  // add the newly created element and it's content into the DOM
  my_div = document.getElementById("org_div1");
  document.body.insertBefore(newDiv, my_div);
}

</script>

<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>

[edit] Notes

If there are known attributes with default values, attribute nodes representing them are automatically created and attached to the element.

To create an element with a qualified name and namespace URI, use the createElementNS method.

Gecko implementation of createElement doesn't conform to the DOM spec for XUL and XHTML documents: localName and namespaceURI are not set to null on the created element. See bug 280692 for details.

[edit] Specification

DOM 2 Core: createElement