jQuery: turning preformatted text into a list

Sometimes using a pre element is not the optimal choice for handling preformatted text. We can turn preformatted text into a list with jQuery. Here's the code:

$(document).ready(function() {

    $('pre.css').each(function() {
    
        var $html = $(this).html();
 
        $(this).replaceWith('<ol class="css">' + $html + '</ol>');
 
 
    });
    
    
    $('ol.css').each(function() {
    
       var items = [];
        var oldHTML = $(this).html();
 
        var lines = oldHTML.split(/\r\n|\n/);
       
       
 
        for(var i=0; i<lines.length; i++) {
 
 var item;
 
 if(lines[i].indexOf('{') != -1 || lines[i].indexOf('}') != -1) {
 
     item = '<li>'+lines[i]+'</li>';
     
 } else {
 
     item = '<li class="indent">' + lines[i] + '</li>';
     
 }
 
 items.push(item);
 
 
        }
 
        for(var j=0; j<items.length; j++) {
 
 
 if(items[j] == '<li></li>' || items[j] == '<li class="indent"></li>') {
 
     items.pop(items[j]);
     
 }
 
        }
 

        var newHTML = items.join('');
 
         $(this).html(newHTML);
    
    
    });
    
    

});

Basically, I've simply replaced a pre element with an ol element. Then I've split up its contents into several lines and formatted them accordingly. You can see the result here.

Note

This demo doesn't work in Internet Explorer.

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

Leave a Reply

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