My newest JavaScript code snippet displays the object hierarchy of a given object and all its childnodes. This comes in pretty handy when working with tables and most certainly even more so when working with
dynamic tables. Sometimes I get so worked up into a project that I can't even think straight and comprehend the invisible processes behind the scenes anymore. Now I have one more neat little helper to prevent this from happening ;^)
And of course, this doesn't work with every browser. I worked hard to make sure of it ;^p Noooo, of course it didn't happen deliberately. But hey, only the Firefox bitches around this time - IE does display it just like my good ol' Opera.
[...](show me)(don't show me)
First let's create a table. Doing that in plain HTML and then showing my function wouldn't really proove the point of it, so let's create a dynamic table (and load this function with <body onload="initthistable();">). I used a "nameless" table (without ID) and threw it into an existing div-box named "daDiv". You can do it however you want, actually.
<<
function initthistable()
{
var i,j, Out = "";
Out += "<table>";
for ( i = 0; i < 4; i++ )
{
Out += "<tr>";
for ( j = 0; j < 3; j++ )
Out += "<td>text "+ i +" "+ j +"</td>";
Out += "</tr>";
}
Out += "</table>";
document.all.daDiv.innerHTML = Out;
}
>>
Add a button to your web page whose onclick loads my function with your root-object (onclick='get_structure( document.all.daDiv );') and this is what you should get:
<<
DIV, daDiv
TABLE
TBODY
TR
TD
#text
TD
#text
TD
#text
TR
TD
#text
TD
#text
TD
#text
TR
TD
#text
TD
#text
TD
#text
TR
TD
#text
TD
#text
TD
#text
>>
Don't like it? Then you can as well quit reading any further (-.-') ... otherwise, here's what my function looks like. Have fun playing with it.
<<
// displays the structural hierarchy of a given object and its childnodes
function get_structure( Obj )
{
var StrucPop = window.open("", "StrucPop", "width=400,height=650,left=400,top=50,scrollbars"),
Out = "";
Out = get_structure_recursive_init( Obj );
StrucPop.document.write( "<html><head> <title>Structure of "+ Obj +"</title> </head>"
+"<body bgcolor=#ffaa44><font face='Terminal' Size=2>" );
StrucPop.document.write( Out );
StrucPop.document.write( "</font></body></html>" );
StrucPop.document.close();
}
// initializes the recursive function that displays the structure of a given object
function get_structure_recursive_init( Obj )
{
if ( Obj != null ) // if it has an ID then print it, too
return Obj.nodeName+ ( ( Obj.id ) ? ", "+ Obj.id : "" )+ GSR_sub( Obj.firstChild, " " )
}
// recursively displays a structure (the actual function that finally does it)
function GSR_sub( Obj, Prefix )
{
if ( Obj == null )
return "";
else
return "<br>"+ Prefix+ Obj.nodeName+ ( ( Obj.id ) ? ", "+ Obj.id : "" )
// depth-first, then same-level-siblings
+GSR_sub( Obj.firstChild, Prefix +" " ) +GSR_sub( Obj.nextSibling, Prefix );
}
>> # top #
1 Comments:
stupid blog formatting ... :^/
Post a Comment