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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

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