Table of contents
- 1. Summary
- 2. Syntax
- 3. Example
- 4. Notes
- 5. Specifications
Summary
In an HTML document creates the specified HTML element.
In a XUL document creates the specified XUL element.
In other documents creates an element with a null namespaceURI.
Syntax
var element = document.createElement(tagName);
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");
newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// 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>
Notes
When called on a document object flagged as an HTML document, createElement lower-cases its argument prior to creating the element.
To create an element with a qualified name and namespace URI, use document.createElementNS()
instead.
Prior to Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)
, you could include angled brackets (< and >) around the tagName in quirks mode; starting in Gecko 2.0, the function behaves the same way in both quirks mode and standards mode.
Specifications
- DOM 2 Core: createElement Gecko implementation of
createElementdoesn't conform to the DOM spec for XUL and XHTML documents:localNameandnamespaceURIare not set tonullon the created element. See bug 280692 for details. - HTML 5: APIs in HTML documents
Mozilla Developer Network