The createElement()
method creates an Element Node from the specified name.
createElement |
Yes | Yes | Yes | Yes | Yes |
document.createElement(nodename)
The required nodename
parameter is a String type
value representing the name of the element you want to create.
An Element object representing the new created Element node.
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:
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:
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: