jQuery Dynamically Create Table

by aherrick 24. June 2010 10:47

Use jQuery objects to build up your table instead of using string concatenation.  How many time have you seen code similar to the following to build up a table?

        $(function () {

            var content = '';
            content += '<div id="tableWrap">';
            content += '<table id="basicTable">';

            for (var i = 0; i < 200; i++) {


                content += '<tr>';
                content += '<td>';
                content += i;
                content += '</td>';
                content += '<td>';
                content += 200 - i;
                content += '</td>';
                content += '</tr>';
            }

            content += '</table>';
            content += '</div>';

            $('body').append(content);
        });

Let's use jQuery's built in ability to build up the objects and take a look at how we could write this differently below.

        $(function () {

            var $wrap = $('<div>').attr('id', 'tableWrap');

            var $tbl = $('<table>').attr('id', 'basicTable');

            for (var i = 0; i < 200; i++) {

                $tbl.append(
                            $('<tr>')
                                    .append($('<td>').text(i),
                                            $('<td>').text(200 - i))
                           );
            }

            $wrap.append($tbl);
            $('body').append($wrap);
        });

View the live code here!

Tags:



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!


Categories

None

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008