JavaScript print_r()

If you are anything like me I constantly fight with having an object/array in JS and I want to see what all of its properties are. I ran into this the other day and decided to actually find a solution to the problem of not knowing what properties there are for an event. While doing some searching I came across this site. It has been a great solution to what I needed. The code is as follows:

   
function print_r(theObj){
   if(theObj.constructor == Array || theObj.constructor == Object){
      document.write("<ul>")
      for(var p in theObj){
         if(theObj[p].constructor == Array || theObj[p].constructor == Object){
            document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
            document.write("<ul>")
            print_r(theObj[p]);
            document.write("</ul>")
         } else {
            document.write("<li>["+p+"] => "+theObj[p]+"</li>");
         }
      }
      document.write("</ul>")
   }
}
 

Its a pretty simple little snippet of code but was VERY handy for me while troubleshooting an event problem and having to deal with each individual browser as each of them have different event properties. Hope it helps someone else.

Leave a Reply