Reputation: 3006
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?
Upvotes: 9
Views: 4210
Reputation: 23642
You could try util-inspect
This is an extraction of Node's
inspect
utility from theutil
module, with two fundamental advantages:
- Single, focused module
- Compatible with all browsers and environments.
Although it is compatible with browsers, it uses CommonJS so needs to be bundled first. But there's a fork that you can load directly in a browser via UNPKG.
Upvotes: 1
Reputation: 225291
Well, here’s something-ish:
function repr(obj) {
if(obj == null || typeof obj === 'string' || typeof obj === 'number') return String(obj);
if(obj.length) return '[' + Array.prototype.map.call(obj, repr).join(', ') + ']';
if(obj instanceof HTMLElement) return '<' + obj.nodeName.toLowerCase() + '>';
if(obj instanceof Text) return '"' + obj.nodeValue + '"';
if(obj.toString) return obj.toString();
return String(obj);
}
It isn’t interactive or comprehensive. If you need that, I can add it, but at a certain point it might just be easier to look at the WebKit developer tools’ source :)
Upvotes: 3
Reputation: 187312
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.
Upvotes: 3