Export (0) Print
Expand All

About Dynamic Content

Note  As of December 2011, this topic has been archived and is no longer actively maintained. For more information, see Archived Content. For information, recommendations, and guidance regarding the current version of Windows Internet Explorer, see Internet Explorer Developer Center.

As of Windows Internet Explorer 8, dynamic properties are obsolete and supported only for Web pages displayed in IE7 Standards mode or IE5 (Quirks) mode. For more information, see Defining Document Compatibility.

Before Microsoft Internet Explorer 4.0, once a Web page was loaded into a user's browser, changing the information displayed on the page required another round-trip to the server. The user interacted with the page (submitted a form, or clicked a link to another page), and the server delivered a new page to the client. Any customization of the information (such as building the page on the fly from a template) required that the server spend additional time processing a page request. Furthermore, the only way to maintain the context for the page's content was to use frame sets, where one frame's content stays constant and another frame changes its content based on the user's activity on the initial page.

Dynamic content is all about changing the content of the HTML document—inserting and deleting elements or the contents of an element before or after the document has been loaded.

Obsolete. Internet Explorer gives you a rich set of properties and methods to dynamically construct and alter Web pages on the fly. For example, a script can insert a list of section titles at the beginning of the document, or replace that list with a list of links to the actual sections in the document.

The following topics show how to dynamically access and modify the content in your Web pages:

Changing HTML Content

Internet Explorer 4.0 provides a set of properties and methods on each element that are designed to make it quite simple to change the document. There are four properties that provide the ability to see what's inside an element on the page and replace that content with new information: innerText, outerText, innerHTML, and outerHTML.

Assigning new text (also called a "string") to one of these properties replaces the contents of the element, including any elements contained by that element, with the new string. Consider the following HTML for an H1 heading.


<H1 id=myH1>Dynamic Content is Very Cool!</H1>

The content of the H1 can be changed with the innerText property.


myH1.innerText = "DHTML is Very Cool"

The H1 element remains in the document, while the content of the H1 changes to contain the new string "DHTML is Very Cool". The string assigned to innerText renders any HTML tags as text, and does not process the HTML. To insert HTML code into the contents of another element, you must use the innerHTML property.


myH1.innerHTML = "DHTML is <I>Very</I> Cool!"

The new string replaces the original content of the H1, and the word "Very" appears in italic.

The outerText and outerHTML properties represent the element itself, as well as the contents of the element. Assuming that the preceding example is contained by a body element, using an outerText property on the H1 replaces the entire element with the string attached. The following script causes the H1 to go away entirely, and the text string appears where the element was in the flow of the body's content.


myH1.outerText = "DHTML is VERY Cool!"

The outerHTML property replaces the element with rich HTML. Much like the example above where HTML was inserted in the H1, using the outerHTML property will do the same, except the H1 would also be removed.


myH1.outerHTML = "<SPAN STYLE='height:0;FILTER:Glow(color=#00AA00)'>VERY Cool</SPAN>";

Note   Setting the height attribute to zero triggers the SPAN element above to obtain layout. Filters can only be applied to elements that have layout.

Click to view sample.

Adding Document Content

The properties described above replace the entire contents of an element with a new string. What if you only want to insert new text or HTML and don't want to change what is already in the document? There are two helper methods on most elements that help you do just this.

These methods, insertAdjacentHTML and insertAdjacentText, place the new content at the beginning or end of the element, leaving the existing content intact. These methods all take a parameter that indicates one of four possible places the new content can be inserted with regard to the element: BeforeBegin, AfterBegin, BeforeEnd, and AfterEnd.

The following example appends a new paragraph to the end of the document when it loads.


<HTML>
<HEAD>
<TITLE>Dynamic Content: Inserting Elements</TITLE>
<SCRIPT LANGUAGE="JScript">
function fnAdd(){
   document.body.insertAdjacentHTML("BeforeEnd", "<P>" + 
      oSelect.value + "</P>");
}
</SCRIPT>
</HEAD>
<BODY>
<P>
<SELECT ID=oSelect>
<OPTION VALUE="Add some <B>Bold</B> text">
Add some &lt;B&gt;Bold&lt;/B&gt; text</OPTION>
<OPTION VALUE="My Dog has the <span style='color:red;letter-spacing:5px'>longest</span> snout">
My Dog has the &lt;span style='color:red;text-spacing:2px'&gt;longest&lt;/span&gt; snout.</OPTION>
<OPTION VALUE="<span onclick=alert('Hello')>Click Me</span>">
&lt;button onclick=alert('Hello')&gt;Click Me&lt;/button&gt;</OPTION>
</SELECT>
<INPUT TYPE=button VALUE="Add" onclick="fnAdd()">
</P>
</BODY>
</HTML>

Click to view sample.

Example: Building a Table of Contents

Building a table of contents is a good example of dynamic content at its best. By using a relatively small amount of script, you can automatically generate a detailed list of the contents of any document.

This example consists of three functions: buildTOC, setAnchor, and setLink. The buildTOC function creates the table of contents, calling the other two functions to apply anchors and insert the links. The example depends on the document having an element, such as div or p, that has the identifier MyTOC. The setLink function inserts the links there. To build the table successfully, buildTOC cannot be called until the document is fully loaded.

Once buildTOC is called, it uses the all collection to check each element to see whether it is a header element: H1, H2, H3, or H4. It starts the search at the first element after the body element since no links are possible before this. When it finds a header, it sets the "level" variable and calls the setAnchor and setLink functions.


function buildTOC() {
    var coll = document.all;
    var level;
    var id;
    for (i=document.body.sourceIndex+1; i<coll.length; i++) {
        switch (coll[i].tagName) {
        case "H1":
            level = 0;
            break;
        case "H2":
            level = 1;
            break;
        case "H3":
            level = 2;
            break;
        case "H4":
            level = 3;
            break;
        default:
            level = -1;
        }
        if (level!=-1) {
            id = i;
            setAnchor(coll[i], id);
            i++;
            setLink(coll[i], level, id);
            i+=2;
        }
    }
}

Notice how the variable "i" is updated after the call to setAnchor and setLink. These functions insert new elements into the document, causing the all collection to be immediately updated and requiring a new index value for the heading. The setAnchor function inserts one element before the heading, so the index is increased by one; the setLink function inserts two elements at the top of the document, so the index is increased by two.

The setAnchor function adds an a element to the document, inserting the start and end tags for this element immediately before and after the header tag, and setting the NAME= attribute of the new element to be equal to the "id" parameter passed to the function.


function setAnchor(el, id) {
    el.insertAdjacentHTML("BeforeBegin", "<A NAME=\"" + id + "\">");
    el.insertAdjacentHTML("AfterEnd", "</A>");
}

The setLink function adds another a element to the document. This time the element is a link to the heading that setAnchor just created an anchor for. The HREF= attribute is set to the same "id" value as was set in the matching anchor. Notice that the setLink function places the link just before the end of the element having the identifier MyTOC, separating it from the previous link with a br element and inserting zero or more nonbreaking spaces for a very simple way to indicate the heading level.


function setLink(el, level, id) {
    MyTOC.insertAdjacentHTML("BeforeEnd", "<BR>");
    var indent = "<A STYLE=margin-left:" + level + "cm ";
    MyTOC.insertAdjacentHTML("BeforeEnd", indent + "HREF=\"#" + id + "\" ">" + el.innerText + "</A>");
}

Click to view sample.

There are a few things to keep in mind when dynamically changing content within a Web page:

The document must be loaded before changing: You may not modify the document content until after the document has been completely loaded and the onload event has fired. If you attempt to change or assign a string to these properties prior to the onload, an error occurs.

The document indexes are updated automatically: The all and other element collections are automatically updated when adding or removing elements. This also affects the sourceIndex for elements following the change. If you have saved the index value of an element, be careful to update that value or retrieve a new value whenever you add or delete elements in a document.

The document must be valid: You cannot assign a string to innerHTML or outerHTML that contains invalid Dynamic HTML (DHTML). For example, trying to insert a p element into another p will fail, since a p element can only contain text and inline elements. However, replacing the entire p element with another p works just fine.

Which Elements Will This Work For?

Here are a few guidelines for which elements you can expect these properties and methods to work.

Only elements that appear in the BODY of the document can be changed with these properties. You can replace the contents of the BODY, but you can't replace the BODY itself.

This should be obvious, but deserves mention anyway: you can't replace the contents of an element where the element type doesn't have any contents like the replaced elements, input and img.

The contents of a td can be changed (innerText and innerHTML) and the table element itself can be replaced (outerText and outerHTML), but no other table elements and their contents can be changed with these properties.

Related topics

Using the TextRange Object
Finding Text in the Document

 

 

Show:
© 2014 Microsoft