简体   繁体   中英

DOM representation of an HTML table

I'm just writing some code to traverse the DOM for a table, and I got a surprise. The DOM (in FF, at least) isn't what I'd expected. FF has inserted a tbody and various text nodes, which just contain a "\\n". The source HTML is:

<table>
<tr>
<th></th><th>Jan</th><th>Feb</th><th>Mar</th><th>Apr</th><th>May</th><th>Jun</th><th>Jul</th><th>Aug</th><th>Sep</th><th>Oct</th><th>Nov</th><th>Dec</th>
</tr>
<tr><th>2010</th>
<td id='tdid0'>53</td>   <td id='tdid1'>249</td>  <td id='tdid2'>1689</td>  <td id='tdid3'>22753</td>
<td id='tdid4'>23051</td><td id='tdid5'>23633</td><td id='tdid6'>23923</td> <td id='tdid7'>23306</td>
<td id='tdid8'>23943</td><td id='tdid9'>24196</td><td id='tdid10'>24440</td><td id='tdid11'>24156</td>
</tr>
<tr><th>2011</th>
<td id='tdid12'>24262</td><td id='tdid13'>22554</td><td id='tdid14'>25507</td><td id='tdid15'>23144</td>
<td id='tdid16'>24354</td><td id='tdid17'>24610</td><td id='tdid18'>24870</td><td id='tdid19'>24424</td>
<td id='tdid20'>24698</td><td id='tdid21'>22640</td><td></td><td></td></tr>
</table>

1 - FF has inserted a tbody as the first child of the table , so I have to go up 3 levels (from a td ) to find the table , not 2

2 - The html view in Firebug shows 3 rows, as expected, where rows 2 and 3 have a th followed by 12 td s. However, when single-stepping through, it turns out that the tbody has 6 children, with a NL text node after each row

3 - Firebug claims that each row has 13 children, as expected (a header and 12 data items). when stepping through the children with nextSibling , though, it turns out that the expected th and td elements are actually separated by text nodes, containing WS. Any idea what's going on? Can the browser basically do what it wants? Thanks.

FF has inserted a tbody

In HTML 4 a tr element may not be a child of a table element. You need a tbody, thead or tfoot element in between. The start and end tags of a tbody element are optional though. Firefox is correctly inserting it.

it turns out that the tbody has 6 children, with a NL text node after each row

You have white space there in your markup

it turns out that the expected th and td elements are actually separated by text nodes, containing WS

Ditto

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM