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:

Save & refresh browser:

Using Javascript to create new elements.

A shiny new h2!

Here's a new paragraph.

Leave a Reply