jQuery: normalizing CSS inline breadcrumbs menus

Suppose that you have a breadcrumbs menu like this:

<ul id="breadcrumbs">
<li>
    <a href="#">Home</a>
    
    <ul>
    
        <li><a href="#">Articles</a>
        
            <ul>
            
                <li><strong>Article</strong></li>
            
            </ul>
        
        </li>
    
    </ul>
    
</li>
</ul>

If you try to apply some styles to this menu, for example by turning each item and unordered list into inline elements with CSS, you'll probably notice that some mysterious gaps will appear between each item. That's due to the indentations applied to the source code. Unfortunately, CSS provides no way to fix this problem. In this case, we should use jQuery to turn the above code into this:

<div id="breadcrumbs">
<a href="#">Home</a>
<a href="#">Articles</a>
<strong>Article</strong>
</div>

Here's the jQuery code:

$(document).ready(function() {

    var html = '';
    
    var a = $('#breadcrumbs')[0].getElementsByTagName('a');
    
    for(var i=0; i < a.length; i++) {
    
        var href = a[i].getAttribute('href');
        var text = a[i].firstChild.nodeValue;
        
        html += '<a href="' + href + '">' + text + '</a>';
    
    
    }
    
    var $strong = $('#breadcrumbs strong').text();
    
    html += '<strong>' + $strong + '</strong>';
    
    $('#breadcrumbs').replaceWith('<div id="breadcrumbs">' + html + '</div>');

});

We're using DOM core methods and a for loop because they are considerably faster than jQuery methods.

4 thoughts on “jQuery: normalizing CSS inline breadcrumbs menus”

  1. Why are you using:

    var a = $('#breadcrumbs')[0].getElementsByTagName('a');

    Instead of:

    var a = $('#breadcrumbs').getElementsByTagName('a');

    I would think that since there should only be one ID for your breadcrumbs that you wouldn't need to specify the first result.

  2. Why not do this:

    .breadcrumbs ul, .breadcrumbs li { display: inline; margin: 0; padding: 0; }


    It seems to work for me, getting rid of all indentation. Granted, the whitespace in the source gets converted to a single space between the individual breadcrumb links but this seems both acceptable and desirable.

Leave a Reply

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