Tuesday, June 24, 2008

JavaScript Object Inspector

Following my previous little JavaScript hack to display the stacktrace in Internet Explorer, I decided to write myself an object inspector. It lists all the properties and all the subproperties of objects.

There is actually nothing fancy about the script, the most important line is for i in o, which in JavaScript lists all property names of an object. The rest is just syntactic sugar - opening the window, defining stylesheet, onclick handler etc.

function v(o, level)
{
	w = window.open('', 'debug');

	if (level == undefined)
	{
		w.document.write('<style>div {border-style:solid;border-width:1pt;margin-left:10pt;padding:2pt;} .v{display:block} .i{display:none}</style>');
		w.document.write('<script>function d(a){a.className=a.className=="v"?"i":"v";}</script>');
		w.document.write('<div class="v">'); 
	}
	else
		w.document.write('<div class="i">'); 

	if (o == undefined)
		w.document.write('undefined <br />');
	else if (typeof (o) == 'object')
		for (i in o)
			if (o[i] != undefined && typeof (o[i]) == 'object') 
			{
				if ((i != 'parentNode') && (i != 'parentElement') && (i != 'nextSibling') && 
				    (i != 'previousSibling') && (i != 'ownerDocument') && (i != 'offsetParent') && 
				    (i != 'ownerElement') && (i != 'document') && (i != 'namespaces') && (i != 'parentTextEdit'))
				{
					w.document.write('<p onclick="d(this.nextSibling);"><b>['+ i +'] = ' + o[i] +'</b></p>');
					v(o[i], 1);
				}
			}
			else if (typeof (o[i]) != 'function')
				w.document.write('<p>['+ i +'] = ' + o[i] +'</p>');

	w.document.write('</div>');
}

To try it out, click on

this link

. A new window should appear listing all the links properties looking something like this.

Tested in Internet Explorer, Firefox and Opera

2 comments:

IMISSMYJUNO said...

Handy! Thanks.

stritti said...

Cool script.
I would like to add it to log4js at http://log4js.berlios.de to log objects details.