buildTree

Build a tree out of selection which returns tag name, class, id, and depth

by elclanrs

HTML

<aside id="leftCol">
    <section class="container"> 
        <header class="child1">
            <hgroup>
                <h1 class="title">Demo Project</h1>
                <h3 class="subTitle">WEBSITE 2011</h3>
            </hgroup>
        </header>

        <div class="child2" id="thisDiv">
            <div class="subChild1">
                <div class="anotherChild1"></div>
                <div class="anotherChild2"></div>
                <div class="anotherChild3"></div>
            </div>

            <div class="subChild2">
                <p>Some Text</p>
            </div>   
        </div>

        <footer class="child3 cacota">                  
            <a href="#">Link to project here</a>
        </footer>
    </section>
</aside>
<div id="tree"></div>

CSS

body { margin: 50px; }
#tree {
    font: normal 12px/1.5 Arial;
}
strong { font-weight: bold; }
.tag {
    float: left;
    clear: both;
    border-left: 1px solid black;
    border-bottom: 1px solid black;
}
.tag:first-child { border: 0; }
.tag a { 
    position: relative;
    top: 15px;
    display: block;
    padding: 0 2em;
    height: 30px;
    line-height: 30px;
    text-decoration: none;
    color: black;
}
.depth1 a {
    position: relative;
    left: -10px;
    top: 0;
    background: black;
    color: white;  
    padding: 1em 3em;  
}
.depth1 a:before {
    content: "";
    position: absolute;
    bottom: 0;
    margin: 0 0 -10px -10px;
    left: 0;
    border-color: transparent black transparent transparent;
    border-style: solid;
    border-width: 10px;  
}
.depth2 a { 
    margin-left: 2em; 
    background: red; 
}
.depth3 a {
    margin-left: 4em; 
    background: yellow; 
}
.depth4 a { 
    margin-left: 6em;
    background: #ccc; }
.depth5 a { 
    margin-left: 8em; 
    background: #eee; 
}

JavaScript

$.fn.buildTree = function () {
    var tree = {};
    this.find('*').andSelf().each(function (i, v) {
        var parents = $(this).parents().length - 1,
        depth = 1;
        while (depth < parents) {
            depth++;
        }
        tree[v.tagName.toLowerCase() + '(' + i + ')'] = {
            id : (v.id) ? '#' + v.id : '',
            klass : (v.className) ? '.' + v.className.replace(' ', '.') : '',
            depth : depth
        };
    });
    return tree;
};

var tree = $('aside').hide().buildTree(),
html = '';
for (var tag in tree) {
    html += '<li class="tag depth' + tree[tag].depth + '"><a href="#">' + tag.match(/\w+/) + tree[tag].klass + tree[tag].id + '</a></li>';
}
$('#tree').append('<ul>' + html + '</ul>');

// Set width
var setMinWidth = function (el) {
    var minWidth = 0;
    el
    .each(function () {
        var width = $(this).width();
        if (width > minWidth) {
            minWidth = width;
        }
    })
    .width(minWidth);
};
setMinWidth($('.tag'));