jQuery: turning a definition list into a table

There are two ways to display an HTML definition list as a table: using CSS floats or replacing the definition list with a real table using jQuery. Let's see the CSS way:

#deflist-1 {

    height: 100%;
    overflow: hidden;
    margin: 0;

}

#deflist-1 dt {

    float: left;
    width: 190px;
    margin: 0;
    padding: 5px;
    background: silver;
    clear: left;

}

#deflist-1 dd {
    
    float: left;
    width: 190px;
    margin: 0;
    padding: 5px;
    background: orange;

}

This solution doesn't work as it is in Internet Explorer 6 and 7 (it works well in IE8, though). The main problem with this solution is that IE needs a container for both the dt and dd elements on each row. More precisely, this solution will work only if we give some additional styles to IE through conditional comments.

Instead, with jQuery the problem is easily fixed. Here's the code:

$(document).ready(function(){

    var html = '<table id="deflist-2">';
    
    $('#deflist-2 dt').each(function(){
    
        var $dt = $(this);
        var $dtContent = $dt.html();
        
        var $ddContent = $dt.next().html();
        
        html += '<tr><td class="dt">' + $dtContent + '</td><td class="dd">' + $ddContent + '</td></tr>';
    });
    
    html += '</table>';
    
    $('#deflist-2').replaceWith(html);

});

With this solution, you avoid any CSS hacks or conditional comments. Anyway, the choice is up to you. You can see the final result here.

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

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

  1. Result! Great fix - thank you! (Not too many people use definition lists, but they should! I'll use them even more now). Thanks again Gabby!

Leave a Reply

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