google chrome remove automatically td when it is not in table and tr

809 Views Asked by At

I noticed to something strange:

when I write the following html (which I know it is not semantically correct)

<!DOCTYPE HTML>
<html>
<head>      
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title></title>
</head>
<body>
    <td><a>test</a></td>
    <td><a>test</a></td>
    <td><a>test</a></td>
    <td><a>test</a></td>
    <td><a>test</a></td>
</body>
</html>

after the page loads chrome decide to removes the td, you can see that in element inspector, but if you do Ctrl+u (view-source:) you see that the td are there...

if I write the HTML like:

<!DOCTYPE HTML>
<html>
<head>      
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title></title>
</head>
<body>
    <table>
        <td><a>test</a></td>
        <td><a>test</a></td>
        <td><a>test</a></td>
        <td><a>test</a></td>
        <td><a>test</a></td>
    </table>
</body>
</html>

it not remove anything it just add the tbody and tr after the page load.

why does it happen? let's say I want to use these tds afterwards with js manipulation? also I did not understand why it is not consistent if it decide to remove I would expect it to remove in all cases.

I decided to share when auto fixing could cause another proble: this is log from console:

// for second example
$('table > td')
[]

$('table >tbody >tr >td')
[<td>​…​</td>​, <td>​…​</td>​, <td>​…​</td>​, <td>​…​</td>​, <td>​…​</td>​]
1

There are 1 best solutions below

1
On
  1. In your first example you give out a non-standard HTML. The browser is eligible to interpret it as it wants. I assume that stripping the non-valid tags is valid. See How do browsers analyze <tr> <td> without <table>? for more details
  2. According to the standard: http://www.w3.org/TR/html401/struct/tables.html the tbody is optional. See Why do browsers insert tbody element into table elements? to understand why the browser automagically adds the tbody element.