Grow your CSS skills. Land your dream job.

Last updated on:

Print Object To Screen

PHP has a nice print_r function for printing out information about a variable to the screen. console.log() is great for that in JavaScript also, but sometimes you just need/want to look at it on the screen.

function print_r(o) {
  return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;'); 
}

So if you have an object like:

var myObject = {
   "lunch": "sandwich",
   "dinner": "stirfry"
};

You could do:

var putHere = document.getElementById("#put-here");

putHere.innerHTML = print_r(myObject);

to see the result on screen.

Also, console.table() is sometimes much better than console.log() for this kind of thing.

Comments

  1. Ben Caplan
    Permalink to comment#

    Great tip Chris! echo '<pre>'; print_r($var); echo '</pre>';is one of the best PHP tools. I use it all the time and I always wished that JS had a comparable method (outside of the console).

    I think that in your last JS code block the ‘#’ in your .getElementById(), should not be there. Also unless I am missing something the first code block is plain old vanilla JS (not jQuery).

    In either case, thanks as always for the awesome tips!

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".