O'Reilly logo

JavaScript Cookbook by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.2. Inserting Elements Before Existing Page Elements

Problem

You need to add a new div element to the web page before an existing div element.

Solution

Use the DOM method createElement to create a new div element. Once created, attach it to the web page before an existing element, using another DOM method, insertBefore:

// get the existing element
var refElement = document.getElementById("sister");

// get the element's parent node
var parent = refElement.parentNode;

// create new div element
var newDiv = document.createElement("div");

// attach to page before sister element
parent.insertBefore(newDiv, refElement);

Discussion

Adding a web page element is uncomplicated, as long as you keep in mind the tree-like structure of the web page. If you’re interested in attaching a web page element before another element, you’ll not only need to access this element, but also the target element’s parent element, in order to create the actual placement.

The reason you need the parent element is that there is no functionality to insert an element before another, given just the target element. Instead, you have to access the target element’s parent element, and use the insertBefore method to insert the new element before the existing one.

In Example 12-1, the solution for this recipe is embedded into a web page that originally consists only of one named div element. When this element receives a click event, a new sister div element is created and inserted into the document before the existing element.

Example 12-1. Inserting a div element into a web page

<!DOCTYPE html>

<head>
<title>object detection</title>
<style type="text/css">
div
{
  width: 50%;
  height: 20px;
  padding: 10px;
  margin: 10px 0;
}

#div1
{
  background-color: #ffff00;
  }

.divclass
{
  background-color: #ccffcc;
}

</style>
<script type="text/javascript">

window.onload=function() {
  document.getElementById("div1").onclick=addDiv;
}

function addDiv() {

  // get parent
  var parent = this.parentNode;

  // create new div
  var newDiv = document.createElement("div");
  newDiv.className = "divclass";
  newDiv.innerHTML = "<p>I'm here, I'm in the page</p>";

  // add to page
  parent.insertBefore(newDiv,this);
}
</script>
</head>
<body>
  <div id="div1">
     <p>Click me to add new element</p>
  </div>
</body>

In the example, since the event is attached to the original div element, a reference to it can be accessed using this within the event function, because the element is the owner of the onclick event handler function. You can then get the element’s parent through the parentNode property. Once you have a reference to both the parent and the existing element, all you need to do is create the new div element and insert it.

Use the document.createElement method, passing in the type of element—in this case, div. Since the current document is an HTML document, the createElement method creates a new HTMLElement, which inherits all functionality of the more generic Element class, as well as additional methods and properties. The new element is assigned a CSS style through the className property, which is a standard property for all HTMLElement objects. It’s given some content using the innerHTML property. The new div element is then added to the web page with insertBefore.

Each successive click of the original div element prepends a new div element to the original, each with the same class and content. Figure 12-1 shows the web page after the original div element has been clicked several times.

Inserting div elements into a web page

Figure 12-1. Inserting div elements into a web page

Namespace Variation

Recipe 11.2 included a discussion on namespaces and their impact on some of the DOM methods that allow us to query and add new web page elements in a document that can contain multiple namespaces. If you’re working within an environment where namespaces are supported, such as an XHTML or SVG document, and you create a new element or attribute, it’s automatically added to the document’s default namespace unless you use one of the namespace-specific DOM methods.

Generally, the default behavior is sufficient. However, if you want to create an element within a specific namespace, such as creating a title in the Dublin Core namespace rather an XHTML title, use the namespace variation of createElement, createElementNS:

var dcTitle = document.createElementNS("http://purl.org/dc/elements/1.1/","title");

The createElementNS takes two parameters: the first is the namespace for the element; the second is the element tag.

The namespace method createElementNS is not supported in HTML currently, as namespaces aren’t supported in HTML. The method is also not currently supported in IE8, but should be in IE9, when Microsoft adds support for XHTML.

See Also

See Recipe 11.2 for more information about namespaces and the DOM. For a specific description of the HTMLElement, see the related W3C page.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required