Generate dynamic content with DOM-2 (Part 1)

Source: Internet
Author: User

Recently, the emergence of peer-to-peer Distributed Computing and the renewed interest in real-time data exchange have eliminated the hot topic of displaying dynamic content on the web. Unfortunately, the stateless nature of HTTP and the limitations of rendering components in different browsers, it brings significant challenges to Web developers who want to pass fresh information to the client and do not want to send additional requests to the server.

To cope with this challenge, developers have rolled back to the use of JavaScript techniques, such as clever usedocument.write() Statement, frameset, andIFRAME, Or useinnerHTML()AndinsertAdjacentHTML() Function to insert new HTML content. This status continues until recently. Although these methods are successful to some extent, they are usually coupled with specific browser implementations. A specific defect of these technologies is that the structure of documents is rarely considered as a problem. In most cases, only one HTML string after another is simply inserted into the page, and nothing is actually being rendered.

Fortunately, with the advent of Web browsers that follow W3, we can now have a better approach. The Document Object Model Level 2 (DOM-2) supported by both ie5 and ns6 browsers provides an interface, this allows developers to instantly generate new HTML after page loading. By calling the DOM-2 method, you can create HTML elements, define the attributes of the elements, and add the elements to the document or existing elements to implement real-time HTML generation. This article will explore some of the basic functions of DOM-2 for generating dynamic content in a browser.

This document assumes that you have a general understanding of the correct document structure and understand the concept of the document as a series of HTML objects with parent-child relationships aggregated together.

Nodes and elements

All the items in the DOM-2 specification that make up a document are called nodes. The node interface provides a series of common methods and attributes, allowing developers to access and operate on all projects in the document.

Like NS6 (Mozilla), IE5 recognizes all projects in HTML documents as elements or text nodes. It is very important to understand the basic differences between elements and text nodes. The element is generally associated with an identifier surrounded by Angle brackets. In HTML, all identifiers are elements, such as <P>, , and <DIV>. An element may also have attributes or contain subnodes.

On the other hand, a text node represents a piece of text. It is different from the element and has no attribute or subnode (although it inherits from the node interface childNodesAnd attribute set ).

Consider the following example code:

<span id="weather">Partly cloudy, scattered showers, high 67</span>

The above code consists of two independent nodes.<SPAN >An identifier is an element node withIDAttribute. InSPANThe text in the middle is actually an independent text node. This node only contains text, no attributes or subnodes.

Element nodes and text nodes have some common attributes:

  • nodeType:This attribute stores a numeric value, corresponding to the node type. ElementnodeTypeThe attribute value is 1, whilenodeTypeThe property value is 3. If you need to examine several unknown node types in the operation, you can use this attribute to differentiate specific node types.
  • nodeName:This property saves a string. And nodeTypeSimilarly, this string corresponds to the node type. All text nodesnodeNameThe attribute values are both "# text ". For elements, itsnodeNameThe property value contains the name of the element identifier. Therefore, an HTML ImagenodeName The property value is "IMG ".
  • nodeValue:This attribute stores the node value, if any. ElementnodeValueThe property value is null. Text NodeNodevalueIs the actual text string contained by this node.

If you need a complete list of node properties and methods, refer to W3C DOM-2 specifications.

Create element and text

The document object contains a series of methods to make it possible to create a new node. These methods are:

  • createElement(String type): Create a new element of the specified type and return a reference to the element.
  • createTextNode(String text): Create a new text node with the content specified by the text parameter and return a reference to the node.
CreateElement

Creating a new element node is unexpectedly simple. You only need to call createElementMethod, and input the expected element type. If you want to perform further operations on the newly created element, it is a good idea to assign the return value of this method, that is, the reference of this newly created element, to a variable.

The following code creates a new paragraph element with no content:

 var newPara = document.createElement("p"); 

NownewParaA variable is a reference to the new paragraph element.

CreateTextNode

You can create a text node in a similar way, that is, callcreateTextNodeMethod to input the text string that you want to add to the new node. Like when creating an element, you can save the returned value to a variable for reference in subsequent code.

 var newText = document.createTextNode("This is a new sentence."); 

The preceding Code creates two new nodes, which cannot be seen in the browser because they are not inserted into the document. The newly created node will float freely in Javascript until you allocate them to a parent object or the object itself.

Each object inherited from the node interface has a nameappendChildSo that other nodes can be inserted to the current node. For exampleappendChild Method, you cannewTextThis new text node is inserted intonewPara Section elements:

var newPara = document.createElement("p");
var newText = document.createTextNode("This is a new sentence.");
newPara.appendChild(newText);

What you need to do now is to insert paragraph elements into the object of the document body. To achieve this, you need to obtainBODYAn element reference. There are several methods to obtain this reference. Most new browsers (ie5 and ns6) allow you to use document.bodyStatement, suchDocument. Body. appendchild (newpara.

A more standard approach is through document objectsgetElementsByTagNameMethod to obtain the first one that can be found in the documentBODY Element reference.

var bodyRef = document.getElementsByTagName("body").item(0);

bodyRef.appendChild(newPara);

Methoditem(0)It is necessary because getElementsByTagNameThe function returns a set of elements found based on the specified identifier name. Because there is usually only one HTML pageBODYIdentity, so you can directly useitem Method to obtain the first item from the set.

There is also a standard method that can be used to obtain reference to the document body, that is, to usegetElementByIdMethod. However, this method assumes that you are not afraid of trouble, for your HTML page <BODY>An ID attribute is assigned to the ID.

<body id="docBody">
var bodyRef = document.getElementById("docBody");
bodyRef.appendChild(newPara);

You can also usegetElementsByTagName AndgetElementByIdThese two methods can be used to obtain references for page objects other than Document Object. For example, click this connection to activate a script that usesgetElementById(The ID attribute of this section element is specified as "example1"), andappendChildMethod To insert a new text node into the section element.

The code for completing the preceding task is as follows:

<Script type = "text/javascript">
Function insertNewText ()
{
Var newText = document. createTextNode
("The DOM method is cool, isn't it? ");
Var para = document. getElementById ("example1 ");
Para. appendChild (newText );
}
</Script>


Because IDThe section element whose attribute value is "example1" already exists in the document'sBODY Element, so there is no need to reference the object. This is a simple example, but the concept shown in this example can be used for other complex DOM operations.

There are some restrictions when creating a new node: one is that the newly created node can only be inserted into the document that creates this node. This means that if you use a series of frames, you cannot create an element in one frame and add it to the Document Object of another frame. Also, it is impossible to pass an element from one window to another.

It is worth mentioning that you are also limited by the logic level of the document and the node type currently being operated. If you try to insert a node into the node itself or its own child node, or insert it into other node objects that do not allow this type of node as the child node, an error may occur.

Where can I use innerhtml?

You may wonder why we need to use these complicated and lengthy JavaScript statements to create a text or HTML element? You can useinnerHTMLTo complete these tasks.

innerHTMLIt is a convenient attribute introduced by Microsoft as an element for reading and writing HTML content. For exampleinnerHTMLStatement, you can easily create a table structure with multiple grids and insert it into your page:

var str = '<table border="1">';
str += '<tr><td>Cell One</td><td>Cell Two?
</td><td>Cell Three</td></tr>';
str += '</table>';
document.all["paragraphOne"].innerHTML = str;

innerHTMLIt has been integrated into Mozilla's code library and is now part of ns6. So why don't we use it? One basic reason is thatinnerHTML It does not return any reference to the node it creates. If, for some reason, you need to modify the secondTDThe text in the element, you cannot find the reference of the second lattice -- and if you usecreateElement()Function, then we already have this reference, because the function always returns the reference of the node. You can usedocument.all,Or even usedocument.getElementById() Function to obtain the reference of the corresponding node, but these methods assume that you have correctly assigned a unique ID for each element in the string. If so, it may be easier to re-write the entire string and insert it into the paragraphone object again.

The method you choose depends on what task you want to complete. If you simply display text or HTML and do not need to access the newly created elements, useinnerHTML. However, if you plan to operate on a specific object in a larger dynamic generation structure, it takes some time to construct the object using the DOM document method.

More node operations

You can also remove existing nodes just like adding new nodes.removeChildThe method allows any node to remove its own child node, as long as you simply input the reference of the node you want to remove. Any element or text in the removed node will also be removed.

When Element B is removed from a paragraphThese black bodiesThe text will also disappear.

<script type="text/javascript">

function removeBElm(){

var para = document.getElementById("example2");

var boldElm = document.getElementById("example2B");

var removed = para.removeChild(boldElm);

}
</script>


Click this connection to see how the above script works.

The removed node is not damaged.removeChildThe function returns a reference to the removed node, so you can perform other operations on the node. Please note that in this example, we assign the removed Element BremovedVariable to maintain a reference of the node.

If you want to remove a nonexistent node or a node labeled as read-only, an error may occur, depending on the browser implementation.

Replace Node

In addition to removing nodes, Dom also provides a method to replace one node with another.replaceChildMethod To achieve this function. AndremoveChildSame method,replaceChildA function must be called by an element containing the node to be replaced.

replaceChildTwo parameters are received: one is the reference of the new node, and the other is the reference of the node to be replaced. The following example creates a newSPANAnd use it to replace the existingSPANElement.

<SCRIPT type = "text/JavaScript">
Function replacespan (){

VaR newspan = Document. createelement ("span ");
VaR newtext =
Document. createtextnode ("Scared ZEBRA ");
Newspan. appendchild (newtext );

VaR para = Document. getelementbyid ("example3 ");
VaR spanelm = Document. getelementbyid ("ex3span ");
VaR replaced = para. replaceChild (newspan, spanelm );
}
</SCRIPT>

You can try this example here:

The agile brown fox jumps on a lazy dog.


Call replacespan ()

Insert in a node Series

You may have noticed that, in the previous example,appendChild The function always uses the newly added node as the last child node of the parent node. In some cases, you may need to insert nodes before or between existing nodes.

insertBefore This node method can achieve this goal.insertBefore Receive two parameters: the new node to be inserted, and the node before which you want to insert. The following example usesinsertBeforeMethod To insert a newTDElement.

<table border="1">
<tr id="example4">
<td>TD One</td>
<td>TD Two</td>
<td>TD Three</td>
</tr>
</table>

<script type="text/javascript">

var TDCount = 0;

function insertTD(){

var newTD = document.createElement("td");
var newText = document.createTextNode("New Cell " + (TDCount++));
newTD.appendChild(newText);

var trElm = document.getElementById("example4");
var refTD = trElm.getElementsByTagName("td").item(2);
trElm.insertBefore(newTD,refTD);

}
</script>

You can try this example here:

TD one TD two TD three



Call inserttd ()

Road ahead

We have discussed how DOM-2 makes real-time HTML generation and page operations so simple, but you may need more powerful functionality. This article does not discuss how to influence the attributes of elements, such as the grid width and background color of a table. In the next article, you will see how to use DOM-2 to manipulate the attributes of elements, and create dynamic effects, you will also see the methods and attributes of some other nodes, and the element interface provided to reference objects in the DOM tree more conveniently.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.