//OUTPUT: Adding elements directly to an output HTML element

<New code>

//PROCESS: var newImageElement = document.createElement( "img" );
— creates a new image element with no source link

//PROCESS: newImageElement.src = "http://drapak.ca/cpg/img/link-up.png";
— adds a source link to the image element
//PROCESS: newImageElement.style.position = "absolute";
— sets the position style of the image element to absolute
//PROCESS: newImageElement.style.top = "10px";
— sets the top position of the image element to 10px
//PROCESS: newImageElement.style.left = "20px";
— sets the left position of the image element to 20px

//OUTPUT: document.getElementById( 'outputID' ).appendChild( newImageElement );
— adds the new image element to the inside of #outputID

Sometimes .innerHTML is slow and confusing

In many of your programs, you will be adding elements to the inside of an HTML element. So far, you code has tended to look a little like this:

document.getElementById( "outputID" ).innerHTML
	= "<p>I'm using Javascript to generate HTML!</p>";

As you can see, there is plenty of opportunities for things to get messed up. If you have:

...then your code will die. As well, using .innerHTML can take a long time to run if you are inserting a lot of images. Each time code is added to a page, the page has to be reflowed to calculate the new positions of the elements. Using .innerHTML can make that take a long time because it has to convert and interpret the HTML code into the internal data structures of the web browser.

The Document Object Model - DOM

<html>
	<head>
		<meta name="author" description="Ford Prefect">
		<style>
			H1 {
				color: red;
			}
		</style>
	</head>
	<body>
		<h1>Hello DOM!</h1>
		<p>
			DOM stands for Document Object Model.
			It represents the way data is stored inside a document
		</p>

		<img id="imageID" src="http://link.to/my.jpg">
			
		<h3>A list of reasons to use DOM programming</h3>
		<ol>
			<li>It sharpens your javascript object skills</li>
			<li>It is considered more elegant, programming-wise</li>
			<li>It displays much faster than .innerHTML</li>
		</ol> 
	</body>
</html>
html
|---head
|    |--meta
|    |   |--name		= author
|    |   |--description	= Ford Prefect
|    |
|    |--style
|        |--h1
|            |--color:	Red
|
|---body
     |--h1
     |   |--Hello DOM!
     |
     |--p
     |   |--DOM stands for Document Object Model.
     |   |--It represents the way data is stored inside a document
     |  
     |--h3
     |   |--A list of reasons to use DOM programming
     |   
     |--img
     |   |--id	 	= imageID
     |   |--src		= http://link.to/my.jpg
     |
     |--ol
         |--li
         |   |--It sharpens your javascript object skills
         |
         |--li
         |   |--It is considered more elegant, programming-wise
         |
         |--li
             |--It displays much faster than .innerHTML

Creating and inserting elements

What if we insert the data directly inside the web browser's Document Object Model?

It turns out that this makes your code run much faster.

And it also turns out that this it also easier and cleaner to code! Take a look at the code examples below. Notice how it is easier to read and there are less places to make mistakes? That is why many programmers prefer to output elements this way.

Example code

//OUTPUT: creating the HEADING!
//example: <h1>'Hello DOM!'</h1>
var createMainHeading = function () {
	console.log( "in createMainHeading..." );
	// make the empty heading element
	var headingElement = document.createElement( 'h1' );
	
	// make the lonely text 
	var headingText = document.createTextNode( 'Hello DOM!' );
	
	// join the text to the heading
	headingElement.appendChild( headingText );
	
	// make the heading purple and computery
	headingElement.style.color      = "purple";
	headingElement.style.fontFamily = "Consolas, Courier New ";
	
	
	// join the heading to #outputID
	document.getElementById( "outputID" ).appendChild( headingElement );
}

//OUTPUT: making the PARAGRAPH
//example: <p>hello there!</p>
var createParagraph = function () {
	console.log( "in createParagraph..." );
	
	// make the empty paragraph element
	var paragraphElement = document.createElement( 'p' );
	
	// make the lonely text 
	var paragraphText 
		= document.createTextNode(
			"DOM stands for Document Object Model."
			+ "It represents the way data is stored inside a document."
		);
	// join the text to the paragraph
	paragraphElement.appendChild( paragraphText );
	
	// make the paragraph be centred
	paragraphElement.style.textAlign = "center";

	// join the paragraph to #outputID
	document.getElementById( "outputID" ).appendChild( paragraphElement );
}

//OUTPUT: making the IMAGE
//example: <img id="imageID" src="http://link.to/my.jpg">
var createImage = function () {
	console.log( "in createImage..." );
	
	// make the empty image element
	var imageElement = document.createElement( 'img' );
	
	// link the image source
	imageElement.src 
		= 'http://drapak.ca/cpg/img/pacman/pacmanGhostFlash2.png';
	
	// add the id
	imageElement.id = 'imageID';
	
	// some positioning
	imageElement.style.position     = "relative";
	imageElement.style.left         = "90%";
	imageElement.style.width        = "60px";
	
	// join the image element to #outputID
	document.getElementById( "outputID" ).appendChild( imageElement );
}

//OUTPUT: making the LIST
//example:  <ol>
//              <li>item number one</li>
//              <li>item number two</li>
//          </ol>
var createList = function () {
	console.log( "in createList..." );
	
	// make the empty list element - <ol>
	var orderedListElement = document.createElement( 'ol' );
	
	// make an array to store the list items - <li>
	var listItemElementArr = [];
	// make the empty list item elements
	listItemElementArr[ 0 ] = document.createElement( 'li' ); 
	listItemElementArr[ 1 ] = document.createElement( 'li' ); 
	listItemElementArr[ 2 ] = document.createElement( 'li' ); 

	// make an array to store the text nodes
	var textNodeArr = [];
	// make the lonely text nodes
	textNodeArr[ 0 ] 
		= document.createTextNode( 
			"It sharpens your javascript object skills" 
		);
	textNodeArr[ 1 ] 
		= document.createTextNode( 
			"It is considered more elegant, programming-wise" 
		);
	textNodeArr[ 2 ] 
		= document.createTextNode( 
			"It displays much faster than .innerHTML" 
		);

	// attach the text nodes to the elements
	// loop through each element, using i as the index variable
	for ( i in listItemElementArr ) {
		// add the text node to this element at index i
		// for example:
		//      listItemElementArr[ 2 ].appendChild( textNodeArr[ 2 ] );
		listItemElementArr[ i ].appendChild( textNodeArr[ i ] );
		
		// add this list item to the main ordered list <ol> element
		orderedListElement.appendChild( listItemElementArr[ i ] )
	}

	// join the completed ordered list element to #outputID
	document.getElementById( "outputID" ).appendChild( orderedListElement );
}


//OUTPUT: making the TABLE
//example:  <table>
//              <thead>
//                  <tr>
//                      <th>heading #0</th>
//                      <th>heading #1</th>
//                      <th>heading #2</th>
//                  </tr>
//              </thead>
//              <tbody>
//                  <tr>
//                      <td>info #0</td>
//                      <td>info #1</td>
//                      <td>info #2</td>
//                  </tr>
//                  <tr>
//                      <td>info #0</td>
//                      <td>info #1</td>
//                      <td>info #2</td>
//                  </tr>
//              </tbody>
//          </table>
var createTable = function () {
	console.log( "in createTable..." );
	
	// make the empty table element - <table>
	var tableElement = document.createElement( 'table' );
	
	// START with the THEAD
	//
	// make the empty <thead> element
	var theadElement = document.createElement( 'thead' );
	
	// make the empty <tr> element
	var theadRowElement = document.createElement( 'tr' );

	// make an array to store the heading elements - <th>
	var headingElementArr = [];
	// make the empty heading elements
	headingElementArr[ 0 ] = document.createElement( 'th' ); 
	headingElementArr[ 1 ] = document.createElement( 'th' ); 
	headingElementArr[ 2 ] = document.createElement( 'th' ); 

	// make an array to store the text nodes
	var headingTextNodeArr = [];
	// make the lonely text nodes
	headingTextNodeArr[ 0 ] 
		= document.createTextNode( 
			"This is some heading text!" 
		);
	headingTextNodeArr[ 1 ] 
		= document.createTextNode( 
			"So is this!" 
		);
	headingTextNodeArr[ 2 ] 
		= document.createTextNode( 
			"And ditto!" 
		);

	// attach the text nodes to the heading elements
	// loop through each element, using i as the index variable
	for ( i in headingElementArr ) {
		// add the text node to this element at index i
		// for example:
		//      headingElementArr[ 2 ].appendChild( headingTextNodeArr[ 2 ] );
		headingElementArr[ i ].appendChild( headingTextNodeArr[ i ] );
		
		// then add this heading element to the table row
		theadRowElement.appendChild( headingElementArr[ i ] )
	}

	// join the completed table row element to the thead
	theadElement.appendChild( theadRowElement );
	// join the completed tbody element to the table
	tableElement.appendChild( theadElement );
	
	// Now with the TBODY
	//
	// make the empty <tbody> element
	var tbodyElement = document.createElement( 'tbody' );
	
	// make the empty <tr> element
	var tbodyRowElement = document.createElement( 'tr' );

	// make an array to store the table data elements - <td>
	var dataElementArr = [];
	// make the empty table data elements
	dataElementArr[ 0 ] = document.createElement( 'td' ); 
	dataElementArr[ 1 ] = document.createElement( 'td' ); 
	dataElementArr[ 2 ] = document.createElement( 'td' ); 

	// make an array to store the text nodes
	var dataTextNodeArr = [];
	// make the lonely text nodes
	dataTextNodeArr[ 0 ] 
		= document.createTextNode( 
			"Look - data number one" 
		);
	dataTextNodeArr[ 1 ] 
		= document.createTextNode( 
			"And it`s cousin, 2!" 
		);
	dataTextNodeArr[ 2 ] 
		= document.createTextNode( 
			"And its best friend, 3?" 
		);

	// attach the text nodes to the table data elements
	// loop through each element, using i as the index variable
	for ( i in dataElementArr ) {
		// add the text node to this element at index i
		// for example:
		//      dataElementArr[ 2 ].appendChild( dataTextNodeArr[ 2 ] );
		dataElementArr[ i ].appendChild( dataTextNodeArr[ i ] );
		
		// then add this table data element to the table row
		tbodyRowElement.appendChild( dataElementArr[ i ] )
	}

	// join the completed table row element to the tbody
	tbodyElement.appendChild( tbodyRowElement );
	// join the completed tbody element to the table
	tableElement.appendChild( tbodyElement );
	
	// make the table element prettier
	tableElement.style.color            = "darkRed";
	tableElement.style.backgroundColor  = "lightGrey";
	tableElement.style.border           = "1px solid black";
	
	// join the complete table element to #outputID
	document.getElementById( "outputID" ).appendChild( tableElement );
}

//INPUT: connect the correct functions to the buttons
document.getElementById( "headingButtonID" ).onclick    = createMainHeading;
document.getElementById( "paragraphButtonID" ).onclick  = createParagraph;
document.getElementById( "imageButtonID" ).onclick      = createImage;
document.getElementById( "listButtonID" ).onclick       = createList;
document.getElementById( "tableButtonID" ).onclick      = createTable;

Learn more