Traversing an HTML table with JavaScript and DOM Interfaces

  • Revision slug: Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
  • Revision title: Traversing an HTML table with JavaScript and DOM Interfaces
  • Revision id: 59748
  • Created:
  • Creator: Sebuls
  • Is current revision? No
  • Comment /* Overview of Sample1.html */

Revision Content

Introduction

This article is an overview of some powerful, fundamental DOM level 1.0 methods and how to use them from JavaScript. You will learn how to create, access and control, and remove HTML elements dynamically. The DOM methods presented here are not specific to HTML; they also apply to XML. The demonstrations provided here will work fine in any browser with full support for DOM level 1, such as the Mozilla browser or others based on it like the next-generation Navigator browser from Netscape. The code samples in this document also work on IE5.

The DOM methods presented here are part of the Document Object Model (Core) level 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML).

Overview of Sample1.html

This article is an introduction to the DOM through sample code. To get started, try out the following HTML sample. It uses DOM level 1 methods from JavaScript to create an HTML table dynamically. It creates a small table with four cells and text content inside each cell. The text content of the cell is: "cell is row y column x" showing the row and column numbers for that cell in the table.

<html>
<head>
<title>Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces</title>
<script>
    function start() {
        // get the reference for the body
        var mybody = document.getElementsByTagName("body")[0];

        // creates a <table> element and a <tbody> element
        mytable     = document.createElement("table");
        mytablebody = document.createElement("tbody");

        // creating all cells
        for(var j = 0; j < 2; j++) {
            // creates a <tr> element
            mycurrent_row = document.createElement("tr");
            for(var i = 0; i < 2; i++) {
                // creates a <td> element
                mycurrent_cell = document.createElement("td");
                // creates a text node
                currenttext = document.createTextNode("cell is row "+j+", column "+i);
                // appends the text node we created into the cell <td>
                mycurrent_cell.appendChild(currenttext);
                // appends the cell <td> into the row <tr>
                mycurrent_row.appendChild(mycurrent_cell);
            }
            // appends the row <tr> into <tbody>
            mytablebody.appendChild(mycurrent_row);
        }
        // appends <tbody> into <table>
        mytable.appendChild(mytablebody);
        // appends <table> into <body>
        mybody.appendChild(mytable);
        // sets the border attribute of mytable to 2;
        mytable.setAttribute("border", "2");
    }
</script>
</head>
<body onload="start()">
</body>
</html>

Note the order in which we created the elements and the text node:

  1. First we created the <table> element.
  2. Next, we created the <tbody> element, which is a child of the <table> element.
  3. Next, we used a loop to create the <tr> elements, which are children of the <tbody> element.
  4. For each <tr> element, we used a loop to create the <td> elements, which are children of <tr> elements.
  5. For each <td> element, we then created the text node with the table cell's text.

Once we have created the <table>, <tbody>, <tr>, and <td> elements and then the text node, we then append each object to its parent in the opposite order:

  1. First, we attach each text node to its parent <td> element using
    mycurrent_cell.appendChild(currenttext);
  2. Next, we attach each <td> element to its parent <tr> element using
    mycurrent_row.appendChild(mycurrent_cell);
  3. Next, we attach each <tr> element to the parent <tbody> element using
    mytablebody.appendChild(mycurrent_row);
  4. Next, we attach the <tbody> element to its parent <table> element using
    mytable.appendChild(mytablebody);
  5. Next, we attach the <table> element to its parent <body> element using
    mybody.appendChild(mytable);

Remember this technique. You will use it frequently in programming for the W3C DOM. First, you create elements from the top down; then you attach the children to the parents from the bottom up.

Here's the HTML markup generated by the JavaScript code:

...
<table border="2">
<tr><td>cell is row 0 column 0</td><td>cell is row 0 column 1</td></tr>
<tr><td>cell is row 1 column 0</td><td>cell is row 1 column 1</td></tr>
</table>
...

Here's the DOM object tree generated by the code for the TABLE element and its child elements:

Image:sample1-tabledom.jpg

You can build this table and its internal child elements by using just a few DOM methods. Remember to keep in mind the tree model for the structures you are planning to create; this will make it easier to write the necessary code. In the <table> tree of Figure 1 the element <table> has one child, the element <tbody>. <tbody> has two children. Each <tbody>'s child (<tr>) has one child (<td>). Finally, each <td> has one child, a text node.

Fundamental DOM Methods - Sample2.html

getElementByTagName is a method of both the Document interface and the Element interface, so both the root document object as well as all Element objects have the getElementByTagName method. To get a list of children of some element, selecting them by tag names, you can use element.getElementsByTagName(tagname).

getElementsByTagName returns a list of child elements that have the specified tagname. From that list of child elements, you can reach an individual element by calling the item method, passing an index for the item number you want returned. The first child element of the list is element number zero. It's easy and very simple but needs attention when you are working with large structures. In the next topic we continue working with the Table sample. The following sample is a simpler one, intended to show some basic methods:

<html>
<head>
<title>Sample code - Traversing an HTML Table with JavaScript and DOM
Interfaces</title>
<script>
    function start() {
        // get a list of all the body elements (there will only be one),
        // and then select the zeroth (or first) such element
        myBody = document.getElementsByTagName("body")[0];

        // now, get all the p elements that are children of the body
        myBodyElements = myBody.getElementsByTagName("p");

        // get the second item of the list of p elements
        myP = myBodyElements[1];
    }
</script>
</head>
<body onload="start()">
<p>hi</p>
<p>hello</p>
</body>
</html>

In this example, we set the myP variable to the DOM object for the second p element inside the body:

  1. First, we get a list of all the body elements via
    myBody = document.getElementsByTagName("body")[0]
    Since there is only one body element in any valid HTML document, this list will have only one item, which we retrieve by selecting the first element in that list using {{mediawiki.external(0)}}.
  2. Next, we get all the p elements that are children of the body via
    myBodyElements = myBody.getElementsByTagName("p");
  3. Finally, we get the second item from the list of p elements via
    myP = myBodyElements[1];

Image:sample2a2.jpg

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

myP.style.background = "rgb(255,0,0)";
// setting inline STYLE attribute

Creating TextNodes with document.createTextNode("..")

Use the document object to invoke the createTextNode method and create your text node. You just need to pass the text content. The return value is an object that represents the text node.

myTextNode = document.createTextNode("world");

This means that you have created a node of the type TEXT_NODE (a piece of text) whose text data is "world", and myTextNode is your reference to this node object. To insert this text into your HTML page, you need to make this text node a child of some other node element.

Inserting Elements with appendChild(..)

So, by calling myP.appendChild({{mediawiki.external('node_element')}}), you are making the element a new child of the second <p> element.

myP.appendChild(myTextNode);

After testing this sample, note that the words hello and world are together: helloworld. So visually, when you see the HTML page it seems like the two text nodes hello and world are a single node, but remember that in the document model, there are two nodes. The second node is a new node of type TEXT_NODE, and it is the second child of the second <p> tag. The following figure shows the recently created Text Node object inside the document tree.

Image:sample2b2.jpg

createTextNode and appendChild is a simple way to include white space between the words hello and world. Another important note is that the appendChild method will append the child after the last child, just like the word world has been added after the word hello. So if you want to append a Text Node between hello and world you will need to use insertBefore instead of appendChild.

Creating New Elements with the document object and the createElement(..) method

You can create new HTML elements or any other element you want with createElement. For example, if you want to create a new <p> element as a child of the <body> element, you can use the myBody in the previous example and append a new element node. To create a node simply call document.createElement("tagname"). For example:

myNewPTAGnode = document.createElement("p");
myBody.appendChild(myNewPTAGnode);

Image:sample2c.jpg

Removing nodes with the removeChild(..) method

Each node can be removed. The following line removes the text node which contains the word world of the myP (second <p> element).

myP.removeChild(myTextNode);

Finally you can add myTextNode (which contains the word world) into the recently created <p> element:

myNewPTAGnode.appendChild(myTextNode);

The final state for the modified object tree looks like this:

Image:sample2d.jpg

Creating a table dynamically (back to Sample1.html)

For the rest of this article we will continue working with sample1.html. The following figure shows the table object tree structure for the table created in the sample.

Reviewing the HTML Table structure

Image:sample1-tabledom.jpg

Creating element nodes and inserting them into the document tree

The basic steps to create the table in sample1.html are:

  • Get the body object (first item of the document object).
  • Create all the elements.
  • Finally, append each child according to the table structure (as in the above figure). The following source code is a commented version for the sample1.html.
At the end of the start function there is a new line of code. The table's border property was set using another DOM method, setAttribute. setAttribute has two arguments: the attribute name and the attribute value. You can set any attribute of any element using the setAttribute method.
<head>
<title>Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces</title>
<script>
    function start() {
        // get the reference for the body
        var mybody = document.getElementsByTagName("body")[0];

        // creates <table> and <tbody> elements
        mytable     = document.createElement("table");
        mytablebody = document.createElement("tbody");

        // creating all cells
        for(var j = 0; j < 2; j++) {
            // creates a <tr> element
            mycurrent_row = document.createElement("tr");

            for(var i = 0; i < 2; i++) {
                // creates a <td> element
                mycurrent_cell = document.createElement("td");
                // creates a Text Node
                currenttext = document.createTextNode("cell is row " + j + ", column " + i);
                // appends the Text Node we created into the cell <td>
                mycurrent_cell.appendChild(currenttext);
                // appends the cell <td> into the row <tr>
                mycurrent_row.appendChild(mycurrent_cell);
            }
            // appends the row <tr> into <tbody>
            mytablebody.appendChild(mycurrent_row);
        }

        // appends <tbody> into <table>
        mytable.appendChild(mytablebody);
        // appends <table> into <body>
        mybody.appendChild(mytable);
        // sets the border attribute of mytable to 2;
        mytable.setAttribute("border","2");
    }
</script>
</head>
<body onload="start()">
</body>
</html>

Manipulating the table with DOM and CSS

Getting a text node from the table

This example introduces two new DOM attributes. First it uses the childNodes attribute to get the list of child nodes of mycel. The childNodes list includes all child nodes, regardless of what their name or type is. Like getElementsByTagName, it returns a list of nodes. The difference is that getElementsByTagName only returns elements of the specified tag name. Once you have the returned list, use {{mediawiki.external('x')}} method to retrieve the desired child item. This example stores in myceltext the text node of the second cell in the second row of the table. Then, to display the results in this example, it creates a new text node whose content is the data of myceltext and appends it as a child of the <body> element.

If your object is a text node, you can use the data attribute and retrieve the text content of the node.
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];

// first item element of the childNodes list of mycel
myceltext=mycel.childNodes[0];

// content of currenttext is the data content of myceltext
currenttext=document.createTextNode(myceltext.data);
mybody.appendChild(currenttext);

Getting an attribute value

At the end of sample1 there is a call to setAttribute on the mytable object. This call was used to set the border property of the table. To retrieve the value of the attribute, use the getAttribute method:

mytable.getAttribute("border");

Hiding a column by changing style properties

Once you have the object in your JavaScript variable, you can set style properties directly. The following code is a modified version of sample1.html in which each cell of the second column is hidden and each cell of the first column is changed to have a red background. Note that the style property was set directly.

<html>
<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);
               // set the cell background color
               // if the column is 0. If the column is 1 hide the cel
               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>
</html>

Revision Source

<h3 name="Introduction"> Introduction </h3>
<p>This article is an overview of some powerful, fundamental DOM level 1.0 methods and how to use them from JavaScript. You will learn how to create, access and control, and remove HTML elements dynamically. The DOM methods presented here are not specific to HTML; they also apply to XML. The demonstrations provided here will work fine in any browser with full support for DOM level 1, such as the Mozilla browser or others based on it like the next-generation Navigator browser from Netscape. The code samples in this document also work on IE5.
</p>
<div class="note">The DOM methods presented here are part of the Document Object Model (Core) level 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML).</div>
<h3 name="Overview_of_Sample1.html"> Overview of Sample1.html </h3>
<p>This article is an introduction to the DOM through sample code. To get started, try out the following HTML sample. It uses DOM level 1 methods from JavaScript to create an HTML table dynamically. It creates a small table with four cells and text content inside each cell. The text content of the cell is: "cell is row y column x" showing the row and column numbers for that cell in the table.
</p>
<pre>&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces&lt;/title&gt;
&lt;script&gt;
    function start() {
        // get the reference for the body
        var mybody = document.getElementsByTagName("body")[0];

        // creates a &lt;table&gt; element and a &lt;tbody&gt; element
        mytable     = document.createElement("table");
        mytablebody = document.createElement("tbody");

        // creating all cells
        for(var j = 0; j &lt; 2; j++) {
            // creates a &lt;tr&gt; element
            mycurrent_row = document.createElement("tr");
            for(var i = 0; i &lt; 2; i++) {
                // creates a &lt;td&gt; element
                mycurrent_cell = document.createElement("td");
                // creates a text node
                currenttext = document.createTextNode("cell is row "+j+", column "+i);
                // appends the text node we created into the cell &lt;td&gt;
                mycurrent_cell.appendChild(currenttext);
                // appends the cell &lt;td&gt; into the row &lt;tr&gt;
                mycurrent_row.appendChild(mycurrent_cell);
            }
            // appends the row &lt;tr&gt; into &lt;tbody&gt;
            mytablebody.appendChild(mycurrent_row);
        }
        // appends &lt;tbody&gt; into &lt;table&gt;
        mytable.appendChild(mytablebody);
        // appends &lt;table&gt; into &lt;body&gt;
        mybody.appendChild(mytable);
        // sets the border attribute of mytable to 2;
        mytable.setAttribute("border", "2");
    }
&lt;/script&gt;
&lt;/head&gt;
&lt;body onload="start()"&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Note the order in which we created the elements and the text node:
</p>
<ol><li> First we created the &lt;table&gt; element.
</li><li> Next, we created the &lt;tbody&gt; element, which is a child of the &lt;table&gt; element.
</li><li> Next, we used a loop to create the &lt;tr&gt; elements, which are children of the &lt;tbody&gt; element.
</li><li> For each &lt;tr&gt; element, we used a loop to create the &lt;td&gt; elements, which are children of &lt;tr&gt; elements.
</li><li> For each &lt;td&gt; element, we then created the text node with the table cell's text.
</li></ol>
<p>Once we have created the &lt;table&gt;, &lt;tbody&gt;, &lt;tr&gt;, and &lt;td&gt; elements and then the text node, we then append each object to its parent in the opposite order:
</p>
<ol>
<li>First, we attach each text node to its parent &lt;td&gt; element using
<pre>mycurrent_cell.appendChild(currenttext);</pre></li>
<li>Next, we attach each &lt;td&gt; element to its parent &lt;tr&gt; element using
<pre>mycurrent_row.appendChild(mycurrent_cell);</pre></li>
<li>Next, we attach each &lt;tr&gt; element to the parent &lt;tbody&gt; element using
<pre>mytablebody.appendChild(mycurrent_row);</pre></li>
<li>Next, we attach the &lt;tbody&gt; element to its parent &lt;table&gt; element using
<pre>mytable.appendChild(mytablebody);</pre></li>
<li>Next, we attach the &lt;table&gt; element to its parent &lt;body&gt; element using
<pre>mybody.appendChild(mytable);</pre></li>
</ol>
<p>Remember this technique. You will use it frequently in programming for the W3C DOM. First, you create elements from the top down; then you attach the children to the parents from the bottom up.
</p><p>Here's the HTML markup generated by the JavaScript code:
</p>
<pre>...
&lt;table border="2"&gt;
&lt;tr&gt;&lt;td&gt;cell is row 0 column 0&lt;/td&gt;&lt;td&gt;cell is row 0 column 1&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;cell is row 1 column 0&lt;/td&gt;&lt;td&gt;cell is row 1 column 1&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
...
</pre>
<p>Here's the DOM object tree generated by the code for the TABLE element and its child elements:
</p><p><img alt="Image:sample1-tabledom.jpg" src="File:en/Media_Gallery/Sample1-tabledom.jpg">
</p><p>You can build this table and its internal child elements by using just a few DOM methods. Remember to keep in mind the tree model for the structures you are planning to create; this will make it easier to write the necessary code. In the &lt;table&gt; tree of Figure 1 the element &lt;table&gt; has one child, the element &lt;tbody&gt;.  &lt;tbody&gt; has two children. Each &lt;tbody&gt;'s child (&lt;tr&gt;) has one child (&lt;td&gt;). Finally, each &lt;td&gt; has one child, a text node.
</p>
<h3 name="Fundamental_DOM_Methods_-_Sample2.html"> Fundamental DOM Methods - Sample2.html </h3>
<p><code>getElementByTagName</code> is a method of both the Document interface and the Element interface, so both the root document object as well as all Element objects have the <code>getElementByTagName</code> method. To get a list of children of some element, selecting them by tag names, you can use <code><var>element</var>.getElementsByTagName(<var>tagname</var>)</code>.
</p><p><code>getElementsByTagName</code> returns a list of child elements that have the specified tagname. From that list of child elements, you can reach an individual element by calling the <code>item</code> method, passing an index for the item number you want returned. The first child element of the list is element number zero. It's easy and very simple but needs attention when you are working with large structures. In the next topic we continue working with the Table sample. The following sample is a simpler one, intended to show some basic methods:
</p>
<pre>&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Sample code - Traversing an HTML Table with JavaScript and DOM
Interfaces&lt;/title&gt;
&lt;script&gt;
    function start() {
        // get a list of all the body elements (there will only be one),
        // and then select the zeroth (or first) such element
        myBody = document.getElementsByTagName("body")[0];

        // now, get all the p elements that are children of the body
        myBodyElements = myBody.getElementsByTagName("p");

        // get the second item of the list of p elements
        myP = myBodyElements[1];
    }
&lt;/script&gt;
&lt;/head&gt;
&lt;body onload="start()"&gt;
&lt;p&gt;hi&lt;/p&gt;
&lt;p&gt;hello&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In this example, we set the <code>myP</code> variable to the DOM object for the second <code>p</code> element inside the body:
</p>
<ol>
<li>First, we get a list of all the body elements via
<pre>myBody = document.getElementsByTagName("body")[0]</pre>
Since there is only one body element in any valid HTML document, this list will have only one item, which we retrieve by selecting the first element in that list using <code>{{mediawiki.external(0)}}</code>.</li>
<li>Next, we get all the p elements that are children of the body via
<pre>myBodyElements = myBody.getElementsByTagName("p");</pre></li>
<li>Finally, we get the second item from the list of p elements via
<pre>myP = myBodyElements[1];</pre></li>
</ol>
<p><img alt="Image:sample2a2.jpg" src="File:en/Media_Gallery/Sample2a2.jpg">
</p><p>Once you have gotten the DOM object for an HTML element, you can set its properties. For example, if you want to set the style background color property, you just add:
</p>
<pre>myP.style.background = "rgb(255,0,0)";
// setting inline STYLE attribute
</pre>
<h4 name="Creating_TextNodes_with_document.createTextNode.28.22...22.29"> Creating TextNodes with <code>document.createTextNode("..")</code> </h4>
<p>Use the document object to invoke the createTextNode method and create your text node. You just need to pass the text content. The return value is an object that represents the text node.
</p>
<pre>myTextNode = document.createTextNode("world");
</pre>
<p>This means that you have created a node of the type TEXT_NODE (a piece of text) whose text data is "world", and myTextNode is your reference to this node object. To insert this text into your HTML page, you need to make this text node a child of some other node element.
</p>
<h4 name="Inserting_Elements_with_appendChild.28...29"> Inserting Elements with appendChild(..) </h4>
<p>So, by calling myP.appendChild({{mediawiki.external('node_element')}}), you are making the element a new child of the second &lt;p&gt; element.
</p>
<pre>myP.appendChild(myTextNode);
</pre>
<p>After testing this sample, note that the words hello and world are together: helloworld. So visually, when you see the HTML page it seems like the two text nodes hello and world are a single node, but remember that in the document model, there are two nodes. The second node is a new node of type TEXT_NODE, and it is the second child of the second &lt;p&gt; tag. The following figure shows the recently created Text Node object inside the document tree.
</p><p><img alt="Image:sample2b2.jpg" src="File:en/Media_Gallery/Sample2b2.jpg">
</p>
<div class="note">createTextNode and appendChild is a simple way to include white space between the words hello and world. Another important note is that the appendChild method will append the child after the last child, just like the word world has been added after the word hello. So if you want to append a Text Node between hello and world you will need to use insertBefore instead of appendChild.</div>
<h4 name="Creating_New_Elements_with_the_document_object_and_the_createElement.28...29_method"> Creating New Elements with the document object and the <code>createElement(..)</code> method </h4>
<p>You can create new HTML elements or any other element you want with createElement. For example, if you want to create a new &lt;p&gt; element as a child of the &lt;body&gt; element, you can use the myBody in the previous example and append a new element node. To create a node simply call <code>document.createElement("tagname")</code>. For example:
</p>
<pre>myNewPTAGnode = document.createElement("p");
myBody.appendChild(myNewPTAGnode);
</pre>
<p><img alt="Image:sample2c.jpg" src="File:en/Media_Gallery/Sample2c.jpg">
</p>
<h4 name="Removing_nodes_with_the_removeChild.28...29_method"> Removing nodes with the <code>removeChild(..)</code> method </h4>
<p>Each node can be removed. The following line removes the text node which contains the word world of the myP (second &lt;p&gt; element).
</p>
<pre>myP.removeChild(myTextNode);
</pre>
<p>Finally you can add myTextNode (which contains the word world) into the recently created &lt;p&gt; element:
</p>
<pre>myNewPTAGnode.appendChild(myTextNode);
</pre>
<p>The final state for the modified object tree looks like this:
</p><p><img alt="Image:sample2d.jpg" src="File:en/Media_Gallery/Sample2d.jpg">
</p>
<h3 name="Creating_a_table_dynamically_.28back_to_Sample1.html.29"> Creating a table dynamically (back to Sample1.html) </h3>
<p>For the rest of this article we will continue working with sample1.html. The following figure shows the table object tree structure for the table created in the sample.
</p>
<h4 name="Reviewing_the_HTML_Table_structure"> Reviewing the HTML Table structure </h4>
<p><img alt="Image:sample1-tabledom.jpg" src="File:en/Media_Gallery/Sample1-tabledom.jpg">
</p>
<h4 name="Creating_element_nodes_and_inserting_them_into_the_document_tree"> Creating element nodes and inserting them into the document tree </h4>
<p>The basic steps to create the table in sample1.html are:
</p>
<ul><li> Get the body object (first item of the document object).
</li><li> Create all the elements.
</li><li> Finally, append each child according to the table structure (as in the above figure). The following source code is a commented version for the sample1.html. 
</li></ul>
<div class="note">At the end of the start function there is a new line of code. The table's border property was set using another DOM method, <code>setAttribute</code>. setAttribute has two arguments: the attribute name and the attribute value. You can set any attribute of any element using the setAttribute method.</div>
<pre>&lt;head&gt;
&lt;title&gt;Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces&lt;/title&gt;
&lt;script&gt;
    function start() {
        // get the reference for the body
        var mybody = document.getElementsByTagName("body")[0];

        // creates &lt;table&gt; and &lt;tbody&gt; elements
        mytable     = document.createElement("table");
        mytablebody = document.createElement("tbody");

        // creating all cells
        for(var j = 0; j &lt; 2; j++) {
            // creates a &lt;tr&gt; element
            mycurrent_row = document.createElement("tr");

            for(var i = 0; i &lt; 2; i++) {
                // creates a &lt;td&gt; element
                mycurrent_cell = document.createElement("td");
                // creates a Text Node
                currenttext = document.createTextNode("cell is row " + j + ", column " + i);
                // appends the Text Node we created into the cell &lt;td&gt;
                mycurrent_cell.appendChild(currenttext);
                // appends the cell &lt;td&gt; into the row &lt;tr&gt;
                mycurrent_row.appendChild(mycurrent_cell);
            }
            // appends the row &lt;tr&gt; into &lt;tbody&gt;
            mytablebody.appendChild(mycurrent_row);
        }

        // appends &lt;tbody&gt; into &lt;table&gt;
        mytable.appendChild(mytablebody);
        // appends &lt;table&gt; into &lt;body&gt;
        mybody.appendChild(mytable);
        // sets the border attribute of mytable to 2;
        mytable.setAttribute("border","2");
    }
&lt;/script&gt;
&lt;/head&gt;
&lt;body onload="start()"&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3 name="Manipulating_the_table_with_DOM_and_CSS"> Manipulating the table with DOM and CSS </h3>
<h4 name="Getting_a_text_node_from_the_table"> Getting a text node from the table </h4>
<p>This example introduces two new DOM attributes. First it uses the <code>childNodes</code> attribute to get the list of child nodes of mycel. The <code>childNodes</code> list includes all child nodes, regardless of what their name or type is. Like getElementsByTagName, it returns a list of nodes. The difference is that getElementsByTagName only returns elements of the specified tag name. Once you have the returned list, use <code>{{mediawiki.external('x')}}</code> method to retrieve the desired child item. This example stores in myceltext the text node of the second cell in the second row of the table. Then, to display the results in this example, it creates a new text node whose content is the data of myceltext and appends it as a child of the &lt;body&gt; element.
</p>
<div class="note">If your object is a text node, you can use the data attribute and retrieve the text content of the node.</div>
<pre>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];

// first item element of the childNodes list of mycel
myceltext=mycel.childNodes[0];

// content of currenttext is the data content of myceltext
currenttext=document.createTextNode(myceltext.data);
mybody.appendChild(currenttext);
</pre>
<h4 name="Getting_an_attribute_value"> Getting an attribute value </h4>
<p>At the end of sample1 there is a call to setAttribute on the mytable object. This call was used to set the border property of the table. To retrieve the value of the attribute, use the getAttribute method:
</p>
<pre>mytable.getAttribute("border");
</pre>
<h4 name="Hiding_a_column_by_changing_style_properties"> Hiding a column by changing style properties </h4>
<p>Once you have the object in your JavaScript variable, you can set style properties directly. The following code is a modified version of sample1.html in which each cell of the second column is hidden and each cell of the first column is changed to have a red background. Note that the style property was set directly.
</p>
<pre>&lt;html&gt;
&lt;body onload="start()"&gt;
&lt;/body&gt;
&lt;script&gt;
    function start() {
       var mybody =document.getElementsByTagName("body")[0];
       mytable     = document.createElement("table");
       mytablebody = document.createElement("tbody");

       for(var j = 0; j &lt; 2; j++) {
           mycurrent_row=document.createElement("tr");
           for(var i = 0; i &lt; 2; i++) {
               mycurrent_cell = document.createElement("td");
               currenttext = document.createTextNode("cell is:" + i + j);
               mycurrent_cell.appendChild(currenttext);
               mycurrent_row.appendChild(mycurrent_cell);
               // set the cell background color
               // if the column is 0. If the column is 1 hide the cel
               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);
    }
&lt;/script&gt;
&lt;/html&gt;
</pre>
Revert to this revision