Javascript Reference - HTML DOM createElement() Method








The createElement() method creates an Element Node from the specified name.

Browser Support

createElement Yes Yes Yes Yes Yes

Syntax

document.createElement(nodename)

Parameter Values

The required nodename parameter is a String type value representing the name of the element you want to create.





Return Value

An Element object representing the new created Element node.

Example

The following code shows how to create a button.


<!DOCTYPE html>
<html>
<body>
<!-- www.j av a 2  s .co m-->
<button onclick="myFunction()">test</button>

<script>
function myFunction() {
    var btn = document.createElement("BUTTON");
    document.body.appendChild(btn);
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to Create a <p> element.


<!DOCTYPE html>
<html>
<body>
<!-- w w w .  j  a v  a  2  s  . co  m-->

<button onclick="myFunction()">test</button>

<script>
function myFunction() {
    var x = document.createElement("P");
    var t = document.createTextNode("This is a paragraph.");
    x.appendChild(t);
    document.body.appendChild(x);
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to create a <p> element and append it to a <div> element.


<!DOCTYPE html>
<html>
<head>
</head><!--from  w ww  . j  ava2  s  .c  o  m-->
<body>
<div id="myDIV">A DIV element</div>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    var x = document.createElement("P");
    var t = document.createTextNode("This is a paragraph.");
    x.appendChild(t);
    document.getElementById("myDIV").appendChild(x);
}
</script>

</body>
</html>

The code above is rendered as follows: