javascript 输出元素的所有设置属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4320356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
output all set attributes of an element
提问by amateur
I have a jquery object which represents a input button element on the page. How can I with jquery to output via console.log all properties/attributes of this element?
我有一个 jquery 对象,它代表页面上的输入按钮元素。如何使用 jquery 通过 console.log 输出该元素的所有属性/属性?
回答by Mike Grace
Assuming the HTML of the page is
假设页面的 HTML 是
<body>
<img id="smile" class="big" alt="smile" madeupattribute="yep" src="http://mikegrace.s3.amazonaws.com/forums/stack-overflow/smile.png"/>
</body>
you could do
你可以
var domElement = $("img")[0] // [0] returns the first DOM element that jQuery found
$(domElement.attributes).each(function(index, attribute) {
console.log("Attribute:"+attribute.nodeName+" | Value:"+attribute.nodeValue);
});
Example page=> http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-get-element-attributes-jquery.html
示例页面=> http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-get-element-attributes-jquery.html
Example page console output
示例页面控制台输出


回答by casablanca
If you want just HTML attributes:
如果你只想要 HTML 属性:
var e = document.getElementById('my_input');
for (var x in e)
if (e.hasAttribute(x))
console.log(x);
If you want all properties that can be retrieved/set via JavaScript:
如果您想要所有可以通过 JavaScript 检索/设置的属性:
var e = document.getElementById('my_input');
for (var x in e)
if (typeof e[x] != 'function')
console.log(x);
Example on JSBin-- for some reason, Firefox fails halfway through the "all properties" list when trying to compute typeof e['selectionStart'].
JSBin 上的示例——出于某种原因,Firefox 在尝试计算typeof e['selectionStart'].

