2012-02-24 93 views
3

是否有一個快捷方式將DOM元素及其各種屬性/值對轉換爲相應的Javascript對象?將DOM元素的屬性/值對轉換成Javascript對象?

例如轉換該HTML頁面:

<div id="snack" type="apple" color="red" size="large" quantity=3></div> 

在JavaScript對象,就好像您已鍵入:

var obj = { 
     id: "snack" 
     type: "apple" 
     color: "red" 
     size: "large" 
     quantity: 3 
}; 
+0

如果有ISN」這是一個插件的好主意。 – Stephen 2012-02-24 22:00:44

回答

5

不是一個真正的捷徑,但至少短期實現,它你想要什麼:

var attributes = document.getElementById('someId').attributes; 
var obj = {}; 

for (var i = 0, len = attributes.length; i < len; i++) { 
    obj[attributes[i].name] = attributes[i].value; 
} 
+1

我可以建議:'(var i = 0,len = attributes.length; i 2012-02-24 22:11:59

+0

同意並更新。即使AFAIK今天的js引擎在第一次擊中並獲得性能之後緩存對象路徑。 – 2012-02-24 22:15:31

+1

我跑了[code](http://jsfiddle.net/sMX4M/),它的工作原理。 – OnesimusUnbound 2012-02-24 22:21:29

1

爲什麼不使用HTML數據和JQuery?

// First, append the attributes with `data-`. 
<div id="snack" data-type="apple" data-color="red" 
    data-size="large" data-quantity="3"></div> 


// Then use jQuery to retrive the data, for this case, 
// the `snack` variable is populated 
var snack = $("#snack").data(); 

for(prop in snack) { 
    alert(prop + " => " + snack[prop]); 
} 

sample code

我不知道,如果你被允許使用jQuery

+0

這太棒了!希望我可以選擇兩個答案。第一個回答如我所問,這對於手頭的任務以一種非常有用的方式重新闡述了這個問題。 – prototype 2012-02-24 22:45:36

1

在更實用的風格,一個聲明:

[].slice.call(attributes).reduce(function(obj,attr){obj[attr.name] = attr.value;return obj;},{})