createElement
Summary
Creates an instance of the element for the specified tag.
Method of dom/Documentdom/Document
Syntax
var element = document.createElement(tagName);
Parameters
tagName
- Data-type
- String
The name of an element. The element may be be an existing DOM element or an extension of a DOM element.
Return Value
Returns an object of type ElementElement
The created element.
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.
<!doctype html>
<html>
<head>
<script>
function create() {
var output, option, newElement, tagSelect, contentSelect;
tagSelect = document.getElementById("tag-select");
contentSelect = document.getElementById("content-select");
output = document.getElementById("output");
output.innerHTML = "";
option = tagSelect.options[tagSelect.selectedIndex];
if (option.text.length > 0) {
newElement = document.createElement(option.textContent);
newElement[option.value] = contentSelect.value;
if (option.textContent === "a") {
newElement.href = "http://www.bing.com";
}
}
output.appendChild(newElement);
}
document.addEventListener("change", create, false);
</script>
</head>
<body>
<select id="tag-select">
<option value="textContent">a</option>
<option value="value">textarea</option>
</select>
<select id="content-select">
<option></option>
<option value="Text">Text</option>
<option value="More and More Text">More and More Text</option>
</select>
<span id="output"></span>
<body>
</html>
Usage
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.
Notes
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.
Related specifications
- DOM Level 3 Core
- Recommendation
See also
Related pages
Reference
- cloneNodecloneNode
Conceptual
About the W3C Document Object Model
Attributions
Microsoft Developer Network: [Windows Internet Explorer API reference Article]