element.dataset in Internet Explorer

后端 未结 4 744
陌清茗
陌清茗 2021-01-06 14:45

I need a way to list the data-* attributes of an element. I would use Object.keys(element.dataset) but IE 9.0 doesn\'t have dataset s

4条回答
  •  温柔的废话
    2021-01-06 14:50

    I needed this but also needed access to the keys, so I wrote a function based on the solution given by Andreas:

    Element.prototype.dataset_simulated = function(){
      var attributes = this.attributes;
      var simulatedDataset = {};
    
      for (var i = attributes.length; i--; ){
        if (/^data-.*/.test(attributes[i].name)) {
          var key = attributes[i].name.replace('data-', '');
          var value = this.getAttribute(attributes[i].name);
          simulatedDataset[key] = value;
        }
      }
      return simulatedDataset;
    };
    

    And to use it, instead of doing element.dataset, you do element.dataset_simulated().

    and here's the fiddle

    Edit:

    It appears that IE<8 also has no support for Element.prototype, so this can simply be a function with usage like dataset_simulated(elem):

    function dataset_simulated(elem){
      var attributes = elem.attributes;
      var simulatedDataset = {};
    
      for (var i = attributes.length; i--; ){
        if (/^data-.*/.test(attributes[i].name)) {
          var key = attributes[i].name.replace('data-', '');
          var value = elem.getAttribute(attributes[i].name);
          simulatedDataset[key] = value;
        }
      }
      return simulatedDataset;
    };
    

提交回复
热议问题