简体   繁体   中英

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?

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

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

在更具功能性的风格中,有一种说法:

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

Why not use HTML data and 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

I'm not sure if you're allowed to use jQuery

Here's how I would do it in 2021.

let attributes = document.getElementById('snacks').attributes
let obj = [...attributes].reduce((o,a)=>{ o[a.name] = a.value; return o},{})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM