2010-12-01 25 views

回答

6

假設頁的HTML是

<body> 
    <img id="smile" class="big" alt="smile" madeupattribute="yep" src="http://mikegrace.s3.amazonaws.com/forums/stack-overflow/smile.png"/> 
</body> 

你可以做

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); 
}); 

例頁 =>http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-get-element-attributes-jquery.html

例頁控制檯輸出

alt text

1

如果你只想HTML屬性:

var e = document.getElementById('my_input'); 
for (var x in e) 
    if (e.hasAttribute(x)) 
    console.log(x); 

如果你想可以檢索/通過JavaScript設置的所有屬性:

var e = document.getElementById('my_input'); 
for (var x in e) 
    if (typeof e[x] != 'function') 
    console.log(x); 

Example on JSBin - 出於某種原因,火狐中途失敗嘗試計算typeof e['selectionStart']時,顯示「所有屬性」列表。