9Dec/094
Debugging Objects in Javascript
There are a lot of good JavaScript debugging tools available out there; FireBug for Firefox comes to mind as one of the best. But when when developing web applications across multiple browsers, particularly browsers like IE which have limited built-in debugging functionality, it's handy to have a function that can be called to debug a specific object on the page.
Here is a JavaScript function that I wrote several years ago. It's a bit of a kludge - I'm sure there is a more elegant approach - but having it available to quickly inspect a single element has saved more than a few hours of painful development:
function debugObject(elem, recurseIntoObjects, elemPropertyName) {
var mesg = "";
if ((elem == undefined) || (elem == null)) {
alert("Passed element is not valid: "+elem);
return;
}
for (var i in elem) {
if ((i == undefined) || (i == null) || (typeof elem[i] == 'function') || (typeof elem[i] == 'undefined') || (elem[i] == null)) {
continue;
}
if (recurseIntoObjects && typeof elem[i] == 'object') {
if ((elemPropertyName != undefined) && (elem[i][elemPropertyName] != 'undefined')) {
mesg += i+": "+elem[i][elemPropertyName]+"\n";
}
else {
var elements = "";
var elementCount = 0;
for (var j in elem[i]) {
if ((j == undefined) || (j == null) || (typeof elem[i][j] == 'function') || (typeof elem[i][j] == 'undefined') || (elem[i][j] == null)) {
continue;
}
if (elementCount != 0) {
elements += ", ";
}
elements += elem[i][j];
elementCount++;
}
mesg += i+"["+elementCount+"]: "+elements+"\n";
}
}
else {
mesg += i+": "+elem[i]+"\n";
}
}
alert(mesg);
return mesg;
}
-
Fortes
-
Mike B.
