Walking the DOM
by Kennethtruyers
HTML
<div id="content">
<h1>Title</h1>
<p>My <em>paragraph</em></p>
</div>
<ul id="resultItems"><li>Click the BODY tag to see it in action</li></ul>
CSS
.prop{
color: Blue;
}
.val{
color: Maroon;
padding-left: 10px;
}
#resultItems{
width: 300px;
position: absolute;
z-index: 1001;
right: 10px;
top: 10px;
box-shadow: 3px 3px 15px 3px #000;
width: 312px;
padding: 10px;
height: 400px;
overflow: auto;
}
#resultItems ul{
margin-top: 0px;
padding-left: 10px;
margin-bottom: 0;
}
#resultItems li{
list-style-type: none;
cursor: pointer;
}
JavaScript
DrawObject("root",document.body, $("#resultItems"));
function DrawObject(prop, obj, parent){
var child = $("<li><span class='prop'>" + escape(prop) + ":</span><span class='val'>" + (isDom(obj) ? obj.tagName : escape(obj)) + "</span></li>");
parent.append(child);
child.on("click.draw", function (e) {
var childList = $("<ul></ul>");
child.append(childList);
if (typeof obj == "object") {
var attribs = [];
for (p in obj) {
attribs.push(p)
}
attribs.sort();
for (var i = 0; i < attribs.length; i++ ) {
DrawObject(attribs[i], obj[attribs[i]], childList);
}
}
child.on("click", function (e) {
childList.toggle();
e.stopPropagation();
});
child.off("click.draw");
e.stopPropagation();
});
}
function escape(txt) {return $('<div/>').text(String(txt)).html().substring(0, 20); }
function isDom(obj){ if (obj != null && obj != undefined){ return obj.nodeType == 1; }
else{ return false; }
}