Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
};
like image 671
prototype Avatar asked Dec 22 '22 01:12

prototype


1 Answers

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;
}
like image 166
Julien May Avatar answered May 12 '23 12:05

Julien May