Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inspect Javascript Objects

How can I inspect an Object in an alert box? Normally alerting an Object just throws the nodename:

alert(document); 

But I want to get the properties and methods of the object in the alert box. How can I achieve this functionality, if possible? Or are there any other suggestions?

Particularly, I am seeking a solution for a production environment where console.log and Firebug are not available.

like image 652
Valentina Avatar asked Mar 18 '11 20:03

Valentina


People also ask

Where is JavaScript in inspect?

With the Chrome browser open, right-click anywhere in the browser window and select Inspect from the pop-up menu. By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements".

How do you console an object in JavaScript?

Console object In JavaScript, the console is an object which provides access to the browser debugging console. We can open a console in web browser by using: Ctrl + Shift + I for windows and Command + Option + K for Mac. The console object provides us with several different methods, like : log()

How do I see objects in console?

Answer: Use console. log() or JSON. stringify() Method You can use the console. log() method, if you simply wants to know what's inside an object for debugging purpose. This method will print the object in browser console.


2 Answers

How about alert(JSON.stringify(object)) with a modern browser?

In case of TypeError: Converting circular structure to JSON, here are more options: How to serialize DOM node to JSON even if there are circular references?

The documentation: JSON.stringify() provides info on formatting or prettifying the output.

like image 92
Torsten Becker Avatar answered Sep 23 '22 23:09

Torsten Becker


The for-in loops for each property in an object or array. You can use this property to get to the value as well as change it.

Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.

For in looks like:

for (var property in object) loop(); 

Some sample code:

function xinspect(o,i){     if(typeof i=='undefined')i='';     if(i.length>50)return '[MAX ITERATIONS]';     var r=[];     for(var p in o){         var t=typeof o[p];         r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+'  ') : o[p]+''));     }     return r.join(i+'\n'); }  // example of use: alert(xinspect(document)); 

Edit: Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.

Edit 2: Well, I wrote one up anyway.

like image 27
Christian Avatar answered Sep 24 '22 23:09

Christian