简体   繁体   中英

Get the HTML table <thead> element using query

I would like to add columns to the heading section of my html table using jquery. This is the definition of the table:

<table id="grid">
    <thead>
            <tr>
        </tr>
    </thead>

    <tbody>

    </tbody>
</table>

And despite I tried to get the reference to append a new th element this way:

$("#grid thead").find("tr").append("<th> elem </th>");

I still haven't succeed to do it. What should I write to refer to the first row of the heading? Thanks for your help.

your code is ok

http://jsbin.com/ufiper/2/edit

are you sure ? see the example attached.

The script clearly works when I adapted it to a standalone page. I added the script inline after the table. So maybe you are using this in the head & need a $(document).ready() or $(window).load() to make sure the code is only executed when the page loads?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>thead test</title>
    </head>
    <body>
        <table id="grid">
            <thead>
                <tr>
                    <td></td>
                </tr>
            </thead>
        </table>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script>
        $(function () {
            $("#grid thead").find("tr").append("<th> elem </th>");
        });
        </script>
    </body>
</html>

The code you've presented is correct. Since it still doesn't work for you, my best guess would be that you've placed this code within your <head></head> . Since the browser read your code top-down and any script gets execute as soon as it is read, at the time it reaches your script, the DOM is not ready, and therefor no element match your selector.

There are two ways to solve this:

  1. Move the code to the end of your body, just before your closing body-tag </body> . Then you know that the element you're selecting is in the DOM.

  2. Wrap your code in a DOM-ready callback, to make sure that the DOM is ready before you execute the code.

Example using a DOM-ready callback:

$(function () {
    $("#grid thead").find("tr").append("<th> elem </th>");
});

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