如何将一个HTML元素作为JavaScript对象记录? [英] How can I log an HTML element as a JavaScript object?

查看:157
本文介绍了如何将一个HTML元素作为JavaScript对象记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用谷歌浏览器,如果您 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,那么我该怎么做?解决方案使用 console.dir

  var element = document.documentElement中; //或任何其他元素
console.log(element); //记录展开式< html> ...< / html>
console.dir(element); //记录元素的属性和值

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

  DIR(元件); //记录元素的属性和值

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



$ p $ Object.keys(element) ; //记录元素的属性名称

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

 键(元件); //记录元素的属性名称

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

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 be inspected by clicking on arrows next to it. If I wanted to see the JavaScript object (with its methods and fields) instead of just the DOM of the element, how would I do that?

解决方案

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.

这篇关于如何将一个HTML元素作为JavaScript对象记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆