Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log an HTML element as a JavaScript object?

Using Google Chrome, if you console.log an object, it lets you inspect the element in the console. For example:

var a = { "foo" : "bar", "whiz" : "bang" };
console.log(a);

This prints out Object which can be inspected by clicking on arrows next to it. If however I try to log an HTMLElement:

var b = goog.dom.query('html')[0];
console.log(b);

This prints out <html></html> which can not be inspected by clicking on arrows next to it. If I want to see the JavaScript object (with its methods and fields) instead of just the DOM of the element, how would I do that?

like image 513
Ben Flynn Avatar asked Mar 09 '12 12:03

Ben Flynn


People also ask

How do you log an object in JavaScript?

Answer: Use console. log() or JSON. stringify() Method You can use the console. log() method, if you simply wants to know what's inside an object for debugging purpose. This method will print the object in browser console.

Is an HTML element an object?

In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.

How do you change an HTML element using JavaScript?

To change HTML element type with JavaScript, we can use the replaceWith method. For instance, we write: const parent = document. createElement("div"); const child = document.


3 Answers

Use console.dir:

var element = document.documentElement; // or any other element
console.log(element); // logs the expandable <html>…</html>
console.dir(element); // logs the element’s properties and values

If you’re inside the console already, you could simply type dir instead of console.dir:

dir(element); // logs the element’s properties and values

To simply list the different property names (without the values), you could use Object.keys:

Object.keys(element); // logs the element’s property names

Even though there’s no public console.keys() method, if you’re inside the console already, you could just enter:

keys(element); // logs the element’s property names

This won’t work outside the console window, though.

like image 107
Mathias Bynens Avatar answered Oct 10 '22 21:10

Mathias Bynens


try this:

console.dir(element)

Reference
[Video] Paul Irish on becoming a console power user.

like image 33
Ross Avatar answered Oct 10 '22 20:10

Ross


Browser print only html part, you can put the element in a object to see dome structure.

console.log({element})
like image 6
Navid Shad Avatar answered Oct 10 '22 21:10

Navid Shad