Converting data-* attributes to an object

后端 未结 4 1307
太阳男子
太阳男子 2021-01-01 12:24

I\'m playing around with the attr-data-* attributes of HTML5 and the corresponding javascript dataset

I\'m doing alot of dynamic form processing, so I end up getting

相关标签:
4条回答
  • 2021-01-01 12:47

    You can use Object.assign

    Object.assign({}, element.dataset) 
    

    For browsers that doesn't support Object.assign you can use polyfill

    0 讨论(0)
  • 2021-01-01 12:49

    in es6 you can use the object spread.
    { ...element.dataset }

    0 讨论(0)
  • 2021-01-01 13:00

    Don't forget about JSON.stringify and JSON.parse.

    var data = document.getElementById('someElement').dataset;
    data = JSON.parse(JSON.stringify(data));
    

    According to Mozilla this should work all the way back to IE 8 without a polyfill.

    0 讨论(0)
  • 2021-01-01 13:04

    Here's a little function to retrieve the element dataset as a normal object:

    function datasetToObject(elem){
        var data = {};
        [].forEach.call(elem.attributes, function(attr) {
            if (/^data-/.test(attr.name)) {
                var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
                    return $1.toUpperCase();
                });
                data[camelCaseName] = attr.value;
            }
        });
        return data;
    }
    

    Scooped up from: Get list of data-* attributes using javascript / jQuery

    0 讨论(0)
提交回复
热议问题