1. Computing

JavaScript By Example

Document Object Model: 17. Create An Element

By

Before we can add a new node into our web page or replace a node in the page with a new node we need to first create the new node that we wish to add. How we do this depends on what type of node that we want to add to the page.

In this example we look at the simplest way of creating a new node that when added to the page will add a new tag into the web page. There are alternate ways of building tables and forms which have their own examples later in this series.

We create a new element node for our web page using the createElement method on the document specifying what type of tag we are creating as the parameter passed to the method. This example shows how to create a new paragraph to be added into the web page. It also shows how we can add attributes to the tag that will be generated - in this instance by adding an id to the paragraph tag.

Note that this code only creates the element, we will look at how to add this node into the web page and how to replace an existing node in the page with this new node in later examples.


var newP;
newP = document.createElement("p");
newP.id = 'new';

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Create An Element

©2014 About.com. All rights reserved.