Jack
Jack

Reputation: 100

JQuery html() function not working correctly with table

<script type="text/javascript">
    $(document).ready(function(){
        console.log($('#list_table_template').html());
    });
</script>

<div id="list_table_template" style="display: none;">
    <table id="list_table" cellpadding="0" cellspacing="0">
        <p>123</p>
        <tr id="lt_header">
            <!--#lt_header#-->
        </tr>
        <!--#lt_listing#-->
        <tr id="lt_footer">
            <td colspan="5">Footer Placeholder</td>
        </tr>
    </table>
</div>

This code is not returning expecting result.

While I was expecting log shows:

    <table id="list_table" cellpadding="0" cellspacing="0">
        <p>123</p>
        <tr id="lt_header">
            <!--#lt_header#-->
        </tr>
        <!--#lt_listing#-->
        <tr id="lt_footer">
            <td colspan="5">Footer Placeholder</td>
        </tr>
    </table>

but instead it gives me:

<p>123</p><table id="list_table" cellpadding="0" cellspacing="0">

    <tbody><tr id="lt_header">
        <!--#lt_header#-->
    </tr>
    <!--#lt_listing#-->
    <tr id="lt_footer">
        <td colspan="5">Footer Placeholder</td>
    </tr>
</tbody></table>

Note the p tag is out of order and jump in front of the table.

Upvotes: 0

Views: 831

Answers (2)

Blazemonger
Blazemonger

Reputation: 92893

You can't nest a paragraph inside a table unless it's inside a <th> or <td> tag. It's invalid HTML, so your browser relocates it outside the table, and jQuery can only read what the browser has parsed.

The best solution might be to replace the p with a caption, which is valid HTML. However, if you want the paragraph to appear inside the table, you need to wrap it in <tr><td>...</td></tr> first.

Upvotes: 7

Gustav Westling
Gustav Westling

Reputation: 633

Your browser can't parse a <p>-tag inside of a <table>. So instead it will be parsed outsise of it.

Upvotes: 0

Related Questions