简体   繁体   English

将 DOM 元素的属性/值对转换为 Javascript object?

[英]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?是否有快捷方式 function 将 DOM 元素及其各种属性/值对转换为相应的 Javascript object?

Eg convert this in the HTML page:例如在 HTML 页面中转换它:

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

to an object in Javascript, as if you had typed:到 Javascript 中的 object,就好像您输入了:

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? 为什么不使用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 示例代码

I'm not sure if you're allowed to use jQuery 我不确定你是否被允许使用jQuery

Here's how I would do it in 2021.以下是我在 2021 年的做法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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