prototype prototype - 4 years ago 81
Javascript Question

Convert attribute/value pairs of a DOM element into a Javascript object?

Is there a shortcut function that converts a DOM element and its various attribute/value pairs to a corresponding Javascript object?

E.g convert this in the HTML page:

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


to an object in Javascript, as if you had typed:

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

Answer Source

Not really a shortcut but at least a short implementation that does what you want:

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download