Dynamic addition of tables using Javascript DOM

Source: Internet
Author: User

A translation technical article has a poor level of English. The translation is also a technology that you just learned at the beginning. Therefore, if you can barely understand English, read the original article as much as possible instead of reading my translation, avoid being misled. Read original
Introduction
This article briefly introduces some basic and powerful methods for DOM 1.0 and how to use them in JavaScript. You can learn how to dynamically create, retrieve, control, and delete HTML elements. These DOM methods also apply to XML. All browsers that fully support DOM 1.0 can run this example well, such as IE5 and Firefox.
Overview-sample1.html
This article introduces DOM through the instance code. Start with the following HTML example. It uses DOM 1 to dynamically create an HTML table from JavaScript. It creates a small table consisting of four cells that contain text content. The text of a cell is "cell is column x of row y", indicating the number of rows and columns of a cell in the table.

<Html>
<Head>
<Title> instance code-use JavaScript and DOM to create an HTML table </title>
<Script> functionstart (){
// Obtain the body tag
Varmybody = document. getElementsByTagName ("body") [0];

//
Create a <table> element and a <tbody> element
Mytable = document. createElement ("table ");
Mytablebody = document. createElement ("tbody ");

// Create all cells
For (varj = 0; j <2; j ++ ){
//
Create a <tr> element
Mycurrent_row =
Document. createElement ("tr ");
For (vari = 0; I <2; I ++ ){
// Create a <td> element
Mycurrent_cell =
Document. createElement ("td ");
// Create a text node

Currenttext =
Document. createTextNode ("cell is the" + j + "Row, the" + I + "column ");
// Add the created text node to <td>
Mycurrent_cell.appendChild (currenttext );
//
Add a column <td> to a row <tr>
Mycurrent_row.appendChild (mycurrent_cell );
}
// Add the row <tr> to <tbody>
Mytablebody. appendChild (mycurrent_row );
}
//
Add <tbody> to <table>
Mytable. appendChild (mytablebody );
// Add <table> to <body>
Mybody. appendChild (mytable );
// Set the border attribute of mytable to 2.
Mytable. setAttribute ("border", "2 ");
} </Script>
</Head>
<Bodyonload = "start ()">
</Body>
</Html>

Note the sequence of creating each element and text node:

1. Create <Table> Elements
2. Create a child element of <Table> <tbody>
3. Use a loop to create <tbody> sub-elements <tr>
4. Use cycles to create sub-elements for each <tr> <TB>
5. Create a text node for each <TB>

After <table>, <tbody>, <tr>, <td> elements and text nodes are created, we add them to their parent nodes in reverse order.
1. Add the created text node to <td>.

Mycurrent_cell.appendChild (currenttext );

2. Add the column <td> to the row <tr>

Mycurrent_row.appendChild (mycurrent_cell );

3. Add the row <tr> to <tbody>

Mytablebody. appendChild (mycurrent_row );

4. Add <tbody> to <Table>

Mytable. appendChild (mytablebody );

5. Add <Table> to <body>

Mybody. appendChild (mytable );

Remember this method. It is often used when you use W3C Dom. First, you create elements from top down and add them to the parent node from bottom up.
This is the HTML generated by JavaScript code:

...
<Tableborder = 5>
<Tr> <td> the cell is 0th rows and 0th columns </td> <td> the cell is 0th rows and 1st columns </td> </tr>
<Tr> <td> the cell is 1st rows and 0th columns </td> <td> the cell is 1st rows and 1st columns </td> </tr>
</Table>
...

This is the DOM object tree of the table elements generated by code and its child elements:

You only need to use a few Dom methods to construct such a table and its sub-elements. Remember to always remember the model tree you will create; this will make code writing easier. In the <Table> tree in the figure, <Table> has a child element <tbody>. <Tbody> there are two child elements. Each <tbody> sub-element (<tr>) has two sub-elements <TD>. Finally, each <TD> has a child element: a text node.
Basic DOM method-sample2.html
The getelementbytagname method applies to documents and elements. Therefore, the root object of a document has the getelementbytagname method like all element objects. You can use element. getelementsbytagname (tagname) to obtain a list of all child elements of an element and select them using the tag name.
Element. getelementsbytagname returns a list of child elements with specific tag names. You can obtain an element from the child element list by calling an item method (passing an index parameter to it. Note that the index of the first child element in the list is 0. Next topic continues with the previous table example. The following example is simpler and shows some basic methods:

<Html>
<Head>
<Title> instance code-use JavaScript and DOM to create an HTML table </title>
<Script> functionstart (){
// Obtain a list containing all body elements (only one)
//
Then select the first element in the list.
MyBody = document. getElementsByTagName ("body") [0];

// Obtain all P elements in the body text element
Mybodyelements =
MyBody. getElementsByTagName ("p ");

// Obtain the second element in the p element list (index starts from 0)
MyP = myBodyElements [1];
} </Script>
</Head>
<Bodyonload = "start ()">
<P> hi </p>
<P> hello </p>
</Body>
</Html>

In this example, we set the myP variable to the DOM object that represents the second p element in the body.
1. Get a list containing all body Elements

MyBody = document. getElementsByTagName ("body") [0];

Because a valid html document has only one body element, this list contains only one element. We can use [0] to select the first element of the list.
2. Obtain all p elements in the blog sub-element

MyBodyElements = myBody. getElementsByTagName ("p ");

3. Select the second item in the p element list.

MyP = myBodyElements [1];


Once you get a DOM object of an html element, you can set its attributes. For example, to set the style background color attribute, you only need to add:

MyP. style. background = "rgb (255, 0, 0 )";

Use document. createtextnode ("..") to create a text node
Use the Document Object To Call The createTextNode method to create your text node. You only need to enter the text content. The returned value is an object that represents the text node.

MyTextNode = document. createTextNode ("world ");

The above Code creates a TEXT_NODE (Text block) node whose text data is "word", and the variable myTextNode points to this Node object. You need to set this text node as the byte point of other node elements to insert this text to your html page.
Insert an element using appendchild (...)
Therefore, by calling myP. appendChild ([node_element]), you can set this text node as the byte point of the Second p element.

MyP. appendChild (myTextNode );

In this example, note that "hello" and "world" are connected together: "helloworld ". So when you see the HTML page, the two text nodes hello and world seem to be a node, but in fact there are two nodes in this document model. The second node is a new text_node node and the second byte of the second p label. The created text node is displayed in the document tree.

Createtextnode and appendchild are simple ways to add spaces between hello and world. Note that the appendchild method will be added to the end of the last subnode, just as the world will be added to the end of hello. Therefore, if you want to add a text node between hello and world, you must use the insertbefore method instead of the appendchild method.

Related Article

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.