使用DOM探索表

时间:2013-03-14 23:00:57

标签: javascript dom

我正在构建一个动态的html表,我想使用DOM进行探索。以下是该表的代码:

<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>

在上面,$nameArray是一个数组数组,每个子数组包括一个名字和一个姓氏。

我正在尝试使用DOM访问HTML表的各种元素。我在我的页面中内置了一个<p id='test'></p>测试区,在那里我可以看到各种DOM语句的含义,例如通过document.getElementById('test').innerHTML=document.getElementById('nameTable').childNodes[2].childNodes[1].innerHTML;

我无法可视化childNodes。更具体地说:

  • getElementById('nameTable').childNodes[2].childNodes[0][object HTMLTableRowElement],我可以使用innerHTML获取值。这包含表格的标题等。
  • childNodes[2].childNodes[2]也是[object HTMLTableRowElement],对应于我桌子的第二行。
  • 这两者之间是childNodes[2].childNodes[1],即[object Text]。正如预期的那样,nodeName#text。但是,其nodeValue为空。我不明白该节点包含什么或如何访问其值。

1 个答案:

答案 0 :(得分:3)

  • 首先,避免像这样使用innerHTML。如果需要,您可以克隆DOM元素。

  • 其次,您的表格缺少<tbody>,这意味着浏览器会为您插入,使您的嵌套.childNodes不准确。

  • 第三,是的,会有文字节点,你可能不会指望它们。页面中的所有内容都表示为节点,因此您需要解决表示空白格式的节点。

  • 最后,表格元素很容易导航,因为它们有自己的自定义集合,因此请使用它们而不是.childNodes。这也解决了文本节点的情况。

    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
    
相关问题