如何将 HTML 元素记录为 JavaScript 对象?

使用 Google Chrome,如果你使用 console.log对象,它可以让你检查控制台中的元素。例如:

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

这将打印出 Object,可以通过点击旁边的箭头来检查。如果我尝试记录一个 HTMLElement:

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

这将打印出无法通过点击旁边的箭头来检查的 <html></html>。如果我想看到 JavaScript 对象(以及它的方法和字段)而不仅仅是元素的 DOM,我该怎么做呢?

97077 次浏览

try this:

console.dir(element)

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

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.

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

console.log({element})