JDelage
JDelage

Reputation: 13672

Exploring a table using DOM

I am building a dynamic html table that I want to explore using DOM. Here is the code for the table:

<table id='nameTable'>
  <col width='5%'/>
  <col width='40%'/>
  <col width='40%'/>
  <col width='5%'/>
  <tr>
    <th rowspan='1' colspan='1'>Modify:</th>
    <th colspan='2'>Name Set Title: <span id="setTitle"><?php echo $setTitle ?></span></th>
    <th rowspan='1' colspan='1'>Remove:</th>
  </tr>
  <tr>
    <th rowspan='1' colspan='1'><input type='checkbox' name='' value='' /> All</th>
    <th colspan='2'>Tags: <span id="tags"><?php
      foreach ($tagArray as $tag){
        echo $tag." ";
      }?></span>
    </th>
    <th rowspan='1' colspan='1'><input type='checkbox' name='' value='' /> All</th>
  </tr>
    <?php 
      foreach ($nameArray as $pair){
        echo
        "<tr>
          <td><input type='checkbox' name='' value=''/></td>
          <td>".$pair[0]."</td>
          <td>".$pair[1]."</td>
          <td><input type='checkbox' name='' value=''/></td>
        </tr>";
      }
    ?>
</table>

In the above, $nameArray is an array of arrays, each sub-array including a first name and a last name.

I'm trying to access various elements of the HTML table using the DOM. I have built into my page a <p id='test'></p> test zone where I can see the meaning of various DOM statements, for example by doing document.getElementById('test').innerHTML=document.getElementById('nameTable').childNodes[2].childNodes[1].innerHTML;

I have trouble visualizing the childNodes. More specifically:

Upvotes: 1

Views: 358

Answers (1)

the system
the system

Reputation: 9336

  • First, avoid use of innerHTML like that. You can clone DOM elements if you need.

  • Second, your table lacks a <tbody>, which means the browser is going to insert it for you, making your nested .childNodes inaccurate.

  • Third, yes, there will be text nodes where you may not expect them. Everything in the pages is represented as a node, so you need to work around nodes representing your white space formatting.

  • Finally, table elements are very easy to navigate, as they have their own custom collections, so use those instead of .childNodes. This also solves the text node situation.

    table.rows[]        // collection of rows in the table
    
    table.tBodies[]     // collection of tbody elements in the table
    
    table.tBodies[0].rows[]           // collection of rows in the first tbody
    
    table.tBodies[0].rows[0].cells[]  // collection of cells in the first row
                                      //                     in the first tbody
    
    table.tHead         // thead element
    table.tHead.rows... // as above
    
    table.tFoot         // tfoot element
    table.tFoot.rows... // as above
    

Upvotes: 3

Related Questions