Reputation: 13672
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:
getElementById('nameTable').childNodes[2].childNodes[0]
is a [object HTMLTableRowElement]
, and I can get the value with innerHTML
. That contains the title of the table, etc. childNodes[2].childNodes[2]
also is a [object HTMLTableRowElement]
that correspond to the 2nd row of my table.childNodes[2].childNodes[1]
, which is a [object Text]
. Its nodeName
is #text
, as expected. However, its nodeValue
is blank. I don't understand what that node contains or how to access its value.Upvotes: 1
Views: 358
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