JavaScript and DOM combinations dynamically create TABLE instances _ Basics

Source: Internet
Author: User
Tags tag name tagname
Brief Introduction
This article briefly describes some of the basic and powerful methods of DOM 1.0 and how to use them in JavaScript. You can learn how to create, acquire, control, and delete HTML elements dynamically. These DOM methods also apply to XML. All browsers that fully support DOM 1.0 can run this example well, such as Ie5,firefox.
profile-sample1.html
This article introduces the DOM through an instance code. Start by trying the following HTML example. It uses the DOM 1 method to dynamically create an HTML table from JavaScript. It creates a small table that consists of four cells that contain text content. The text of the cell is: "Cell is row x column Y", which represents the number of rows and columns of cells in the table.
Copy Code code as follows:

<title> instance code-creating HTML tables using JavaScript and Dom </title>
<script>
function Start () {
Get body Tag
var mybody = document.getElementsByTagName ("body") [0];

Create a <table> element and a <tbody> element
MyTable = document.createelement ("table");
Mytablebody = document.createelement ("tbody");

Create all cells
for (var j = 0; J < 2; J + +) {
Create a <tr> element
Mycurrent_row = Document.createelement ("tr");
for (var i = 0; i < 2; i++) {
Create a <td> element
Mycurrent_cell = document.createelement ("TD");
Create a text node
Currenttext = document.createTextNode ("Cell is +j+" row, paragraph "+i+" column);
Add the created text node to <td>
Mycurrent_cell.appendchild (Currenttext);
Add column <td> to row <tr>
Mycurrent_row.appendchild (Mycurrent_cell);
}
Add line <tr> to <tbody>
Mytablebody.appendchild (Mycurrent_row);
}
Add <tbody> to <table>
Mytable.appendchild (Mytablebody);
Add <table> to <body>
Mybody.appendchild (mytable);
Set the Border property of the table MyTable to 2
Mytable.setattribute ("Border", "2");
}
</script>
<body onload= "Start ()" >
</body>


notice the order in which we create the elements and the text nodes

1. Create < table > elements
2. Create < table > child elements < tbody >
3. Use a loop to create the child elements of < tbody > < tr >
4. Use loops for each < tr > Create child elements < TB >
5. Create a text node for each < TB >

After creating the < table >,< tbody >,< TR >,< td > Elements and Text nodes, we add them separately to our parent node in the reverse order.
1. Add the created text node to < td >

Mycurrent_cell.appendchild (Currenttext);

2. Add columns < td > To line < tr >

Mycurrent_row.appendchild (Mycurrent_cell);

3. Add line < 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 the DOM. First, you build the elements from the top down, and then you add them from the bottom up to the parent node.
This is the HTML generated by JavaScript code:

...
<table border=5>
<tr><td> cell is line No. 0, column No. 0 </td><td> cell is line No. 0, 1th column </td></tr>
<tr><td> cell is line 1th, column No. 0 </td><td> cell is line 1th, 1th column </td></tr>
</table>
...

This is the code-generated TABLE element and the DOM object Tree of its child elements:

You can construct such a table and its child elements with only a small number of DOM methods. Remember to keep in mind the structure of the model tree you will create, which makes writing code simpler. In the diagram < table > Tree,< table > has a child element < tbody >. < tbody > has two child elements. Each child element of < Tbody > (< tr >) has two child 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, so the document root object has the same Getelementbytagname method as all element objects. You can use Element.getelementsbytagname (tagname) to get a list of all the child elements of an element and select them using the tag name.
Element.getelementsbytagname returns a list of child elements that have a specific label name. You can get an element from the list of child elements by calling an Item method (passing an index argument to it). Note that the index of the first child element in the list is 0. The next topic continues with the previous table example. The following example is simpler and shows some basic methods:

Copy Code code as follows:

<title> instance code-creating HTML tables using JavaScript and Dom </title>
<script>
function Start () {
Gets a list that contains all the body elements (there will be only one)
Then select the first element in the list
Mybody = document.getElementsByTagName ("body") [0];

Gets all the P elements in the body word element
Mybodyelements = Mybody.getelementsbytagname ("P");

Gets the second element of the P-element list (index starting from 0)
MYP = mybodyelements[1];
}
</script>
<body onload= "Start ()" >
<p>hi</p>
<p>hello</p>
</body>

In this example, we set the MYP variable to represent a DOM object that represents the second P element in the body.
1. Get a list that contains all the body elements

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

Because a valid HTML document has only one BODY element, the list says only one. We get it by using [0] to select the first element of the list.
2. Get all P elements in the blog child element

Mybodyelements = Mybody.getelementsbytagname ("P");

3. Select the second item of the P element list

MYP = mybodyelements[1];


Once you get the DOM object of an HTML element, you can set its properties. For example, you want to set the style background color property, just add:

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

Use document.createTextNode ("..") Create a text node
Use the Document object to invoke the createTextNode method to create your text node. You only need to enter text content. The return value is an object that represents this text node.

Mytextnode = document.createTextNode ("World");

The above code creates a text data that is the Text_node type (text block) node of Word, and the variable Mytextnode points to the node object. You need to set this text node to be a byte point for other node elements to insert this text into your HTML page.
Using AppendChild (..) inserting elements
So, by calling Myp.appendchild ([node_element]), you set this text node to be the byte point of the second P element.

Myp.appendchild (Mytextnode);

To test this example, note that "Hello" and "world" two words are linked together: "HelloWorld". So when you see the HTML page, the two text nodes Hello and world look like a node, and in fact there are two nodes in the document model. The second node is a new Text_node type node and is the second byte point of the second P tag. The following figure shows the text node that you just created in the document tree.

createTextNode and AppendChild are an easy way to add spaces between Hello and world. A special note is that the AppendChild method will be added behind the last child node, just as world is added to hello behind. So if you want to add a text node between Hello and world, you need to use the InsertBefore method instead of the appendchild.

Working with document objects and createelement (..) method to create a new element
You can use the CreateElement method to create new HTML elements or any other elements you want. For example, if you want to add a byte point < p > element for the < BODY > element, you can add a new element node using the Mybody in the precedent. Creating a node requires only calling Document.createelement ("TagName"). For example:

Mynewptagnode = document.createelement ("P");
Mybody.appendchild (Mynewptagnode);


Using RemoveChild (..) method to delete a node
Each node can be deleted. The following line of code deletes the text node in MYP (the second < p > Element) that contains the word world.

Myp.removechild (Mytextnode);

Finally you can add the text node Mytextnode that contains the word world to the newly created < p > elements:

Mynewptagnode.appendchild (Mytextnode);

Fixed object Tree last like this:

Create a table dynamically (back to sample1.html)
The remainder of the article will return to sample1.html. The following illustration shows the object tree structure of the table created in the example.
Review HTML table structure

Create element nodes and add them to the document tree
Basic steps for creating a table in sample1.html:

Get the Body object (the first item of the Document object) create all the elements finally, add each byte point according to the table structure on the diagram below the source code is sample1.html's comment

There is a new line of code at the end of the start function, and the border property of the table is set using another Dom method setattribute. The SetAttribute method has two parameters: a property name and a property value. You can use the SetAttribute method to set any attribute of any element.

Copy Code code as follows:

<title> instance code-creating HTML tables using JavaScript and Dom </title>
<script>
function Start () {
Get body
var mybody = document.getElementsByTagName ("body") [0];

Creating <table> and <tbody> elements
MyTable = document.createelement ("table");
Mytablebody = document.createelement ("tbody");

Create all cells
for (var j = 0; J < 2; J + +) {
Create a <tr> element
Mycurrent_row = Document.createelement ("tr");

for (var i = 0; i < 2; i++) {
Create a <td> element
Mycurrent_cell = document.createelement ("TD");
Create a text node
Currenttext = document.createTextNode ("Cell is the first" + j + "row, the first" + i + "column");
Add the created text node to the <td> element
Mycurrent_cell.appendchild (Currenttext);
Add <td> to <tr> line
Mycurrent_row.appendchild (Mycurrent_cell);
}
Add <tr> line to <tbody>
Mytablebody.appendchild (Mycurrent_row);
}

Add <tbody> to <table>
Mytable.appendchild (Mytablebody);
Add <table> to <body>
Mybody.appendchild (mytable);
Set the Border property of the mytable to 2;
Mytable.setattribute ("Border", "2");
}
</script>
<body onload= "Start ()" >
</body>

Working with tables using DOM and CSS
get a text node from the table
This example describes two new Dom properties. First, use the ChildNodes property to get the list of byte points for the mycel. This childnodes list contains all the byte points, regardless of their name and type. Like the getElementsByTagName method, it returns a list of Word nodes, using [x] to get the desired byte point items. This example stores myceltext as the text node for the second cell in the second row of the table. Finally, it creates a new text node that contains the Myceltext data property and makes it the child node of the < BODY > element to display the final result of the example.

If your object is a text node, you can use the Data property to get its contents

Copy Code code as follows:

Mybody = document.getElementsByTagName ("body") [0];
MyTable = mybody.getelementsbytagname ("table") [0];
Mytablebody = Mytable.getelementsbytagname ("tbody") [0];
Myrow = Mytablebody.getelementsbytagname ("tr") [1];
Mycel = Myrow.getelementsbytagname ("TD") [1];

Mycel the first item in the list of byte points
Myceltext=mycel.childnodes[0];

Currenttext's content is Myceltext's data.
Currenttext=document.createtextnode (Myceltext.data);
Mybody.appendchild (Currenttext);


gets a property value
At the end of the sample1 there is a cell that uses the SetAttribute method of the MyTable object. This cell is used to set the border property of this table. Use the GetAttribute method to get this property:

Mytable.getattribute ("border");

Hide columns by changing the style property
When you use a JavaScript variable to point to an object, you can set its Style property immediately. The following code is modified by sample1.html, the cells in the second column are hidden, and the cell background of the first column is changed to red. Note The Style property is set directly.

Copy Code code as follows:

<body onload= "Start ()" >
</body>
<script>
function Start () {
var mybody =document.getelementsbytagname ("body") [0];
MyTable = document.createelement ("table");
Mytablebody = document.createelement ("tbody");

for (var j = 0; J < 2; J + +) {
Mycurrent_row=document.createelement ("tr");
for (var i = 0; i < 2; i++) {
Mycurrent_cell = document.createelement ("TD");
Currenttext = document.createTextNode ("Cell is:" + i + j);
Mycurrent_cell.appendchild (Currenttext);
Mycurrent_row.appendchild (Mycurrent_cell);
If you set the cell background color in column No. 0
If you hide cells in column 1th
if (i = = 0) {
Mycurrent_cell.style.background = "RGB (255,0,0)";
} else {
Mycurrent_cell.style.display = "None";
}
}
Mytablebody.appendchild (Mycurrent_row);
}
Mytable.appendchild (Mytablebody);
Mybody.appendchild (mytable);
}
</script>

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.