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

Ben*_*ynn 72 javascript google-chrome developer-tools google-closure-library

使用谷歌浏览器,如果你console.log是一个对象,它可以让你检查控制台中的元素.例如:

var a = { "foo" : "bar", "whiz" : "bang" };
console.log(a);
Run Code Online (Sandbox Code Playgroud)

Object通过单击旁边的箭头打印出可以检查的内容.但是,如果我尝试记录HTMLElement:

var b = goog.dom.query('html')[0];
console.log(b);
Run Code Online (Sandbox Code Playgroud)

<html></html>通过单击旁边的箭头打印出无法检查的内容.如果我想看到JavaScript对象(带有方法和字段)而不仅仅是元素的DOM,我该怎么做?

Mat*_*ens 141

用途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
Run Code Online (Sandbox Code Playgroud)

如果你已经在控制台内,你可以简单地键入dir而不是console.dir:

dir(element); // logs the element’s properties and values
Run Code Online (Sandbox Code Playgroud)

要简单地列出不同的属性名称(没有值),您可以使用Object.keys:

Object.keys(element); // logs the element’s property names
Run Code Online (Sandbox Code Playgroud)

即使没有公共console.keys()方法,如果你已经在控制台内,你可以输入:

keys(element); // logs the element’s property names
Run Code Online (Sandbox Code Playgroud)

但是,这在控制台窗口之外不起作用.

  • 当我直接在控制台中使用 console.dir() 时,它可以工作。但是,如果我将其写入 VS Code 中的实际 .js 文件中,则 chrome 开发控制台只会记录写入文件的名称和行号。你知道为什么吗? (3认同)

Nav*_*had 10

浏览器仅打印 HTML 部分,您可以将元素放在对象中以查看 DOM 结构。

console.log({element})
Run Code Online (Sandbox Code Playgroud)