jQuery: turning a list into a table

In order to create a basic image gallery with CSS, we're usually accustomed to use floats to get the desired effect. However, floats sometimes can be really buggy in Internet Explorer and require a lot of workarounds to get them fixed. On the other hand, tables are a safer way to accomplish our task. However, since tables should be used only for tabular data and not for presentational purposes, we stick to a basic unordered list in our markup:

<ul id="gallery">

<li><img src="img/1.jpg" alt="Image" />

<li><img src="img/2.png" alt="Image" />

<li><img src="img/3.jpg" alt="Image" />


Then we want to turn this list into a table by using jQuery. First of all, we need some basic styles to keep our gallery organized:

#gallery {

    width: 456px;
    margin: 0 auto;
    border-collapse: collapse;
    table-layout: fixed;


#gallery td {

    width: 147px;
    padding-right: 5px;


#gallery td img {

    display: block;
    width: 100%;


#gallery td p {

    margin: 0;
    padding: 0.3em 0;
    text-align: center;
    text-transform: uppercase;


Now we can add jQuery:


    var html = '';
    html += '<table id="gallery">';
    html += '<tr>';
    $('#gallery li').each(function() {
        var $li = $(this);
        var imgSrc = $li.find('img').attr('src');
        var imgAlt = $li.find('img').attr('alt');
        var caption = $li.find('p').text();
        html += '<td><img src="'+imgSrc+ '" alt="'+imgAlt+ '"/>'+'<p>'+caption+'</p></td>';
    html += '</tr>';
    html += '</table>';


You can see the final result here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: turning a list into a table”

  1. There's a little inconvenience in doing this.
    The generated content (via javascript) will be obviously disattending to that rule: we'll have a TABLE without tabular data.
    I often met this kind of behaviour - keep the code clean and then manipulate the DOM via javascript - but I still think that's not fair.
    It's the same that avoiding using "target" deprecated (in XHTML) attribute and then manage links with "window.open()".
    I still think it's unfair. :)

Leave a Reply

Note: Only a member of this blog may post a comment.