How to get console.log result string in javascript code?
For example, if I enter $("p") in the chrome console, I get [<p>Text1</p>,<p>..</p>] , and that is exactly what I want. Now I want to save the result string in a variable and reuse it later, but I have not yet been able to find a way ( $("p").toString() gets [Object Object] ).
Is there a way to get the result string of console.log in code?
You can not. console.log does some magic that a string cannot do. It does not just display the object as a string. It also makes the structure of an object interactive and interactive. It provides several interactive elements. The dev panel takes a reference to the object and displays it outside of where you can reach the code.
But, as @minitech notes, you can come close to JSON.stringify(myObject) .
var myObject = { a: 1, b: 2 }; myObject.toString(); // [object Object] JSON.stringify(myObject); // {"a":1,"b":2} Although this will not work with DOM elements, as they usually have round links. So you have to write your own function to traverse the jQuery object and dump it into a string. Nothing has been done for you to do this for you.
Well, 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 is not interactive or comprehensive. If you need it, I can add it, but at some point it might be easier for you to look at the source of WebKit developer tools :)