Creating Elements

To create an element:

  1. Create the element, using the .createElement() method
  2. Add text (if required), using either the .innerHTML or .createTextNode() method
  3. Add it to the DOM, using the .appendChild() method


var newElem = document.createElement("p") ; //passing in the type of element as a string in quotes


At this point the newly created element is empty and not attached to the DOM.


Therefore to add content to the element, we can either use:


.innerHTML method:


newElem.innerHTML = "Text for newly created element." ;

Now the new element has content it can be attached to the DOM, using theĀ appendChild() method to add it to an existing element:

myExisting.appendChild(newElem) ;


Or the more 'correct' approach of adding a text node:


var newText = document.createTextNode("Text for newly created element.") ;

newElem.appendChild(newText) ;


Again, this is not associated with anything and therefore has to be attached to the target element using the appendChild() method:


myExisting.appendChild(newElem) ;



Example showing above approaches to create new elements:

		<div id="myDiv">
			<h1>Using Javascript to create new elements.</h1>
			//create a handle to append new elements to
			var myExisting = document.getElementById('myDiv');

			//create new element
			var newHead = document.createElement("h2");
			//assign text to new element
			newHead.innerHTML = "A shiny new h2!";
			//append new element to existing element

			//create new element
			var newPara = document.createElement("p");
			//create new text node
			var newText = document.createTextNode("Here's a new paragraph.");
			//assign text to new element
			//append new element to existing element

Save & refresh browser:

Using Javascript to create new elements.

A shiny new h2!

Here's a new paragraph.

Leave a Reply