How to get result string of console.log in javascript code?

javascript

Solution

You can't. `console.log` does some magic that a string cant do. It doesn't just render the object as a string. It also make the object structure interactive and clickable. It's rendering multiple interactive elements. The dev panel is taking a reference to an object and rendering it outside of where you code can reach.

But as @minitech notes, you can get close with `JSON.stringify(myObject)`.

var myObject = { a: 1, b: 2 };
myObject.toString();      // [object Object]
JSON.stringify(myObject); // {"a":1,"b":2}

Though this won't work with DOM elements, as they typically have circular references. So you'd have to write your own function to crawl a jQuery object and dump it to a string. There isn't anything built in to do it for you.

Problem

For example, if I enter `$("p")` in the chrome console, I get `[<p>Text1</p>,<p>..</p>]` , which is just what I want. Now I want to store the result string to a variable and reuse it later, but i couldn't find a way yet ( `$("p").toString()` gets `[Object Object]`). Is there a way to get the result string of `console.log` in code?

Original source