JavaScript document.createElement()

Document.createElement()  is used for creating element node. In HTML document, it creates specified HTML element .In other words it creates an instance of element for the specified tag. In document.createElement (), the element creates the element interface as soon it’s created. To create a text button, text node is created. The document.createElement( ) is supported by almost all browser such as Internet Explorer, Firefox, Opera, Google Chrome, and Safari etc.

Document.createElement  Syntax

var element=document.createElement(tagName);

where, element is created element object and tagName is string which indicates type of the element to be created.

Document.createElement Example

The following example shows use of document.createElement() method:

<!DOCTYPE html>
<head>
<title>Insert title here</title>
</head>
<body>

	<button onclick="myExample()">Click Here</button>
	<script type="text/javascript">
		function myExample() {
			var myButton = document.createElement("Button");
			var a = document.createTextNode("Hello")
			myButton.appendChild(a);
			document.body.appendChild(myButton);

		}
	</script>

</body>
</html>
  • <button onclick=”myExample()”>Click Here</button> tag creates button called Click Here and uses onclick() function which perform click event on the button.
  • var myButton = document.createElement(“Button”);line creates instance of the element for specified tag using document.createElement() method.
  • var a = document.createTextNode(“Hello”) line creates text node with specified text.
  • myButton.appendChild(a); line adds new child node of the specified element node.

Document.createElement Demo

  • Save the file as docCreateElement.html in your system.
  • Just open the file in the browser, you will see the below picture in the browser.

When the execution process is completed successfully we will get the following output:

JavaScript document.createElement()

Now click on the button “click here” and you will as in the screen below a new element is created.
JavaScript document.createElement 1

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*