Saving certain attributes of symbol data in an object

I have a div tag something like below

<div class="class" data-mark-comp="comp1" data-conf-property1="p1" data-conf-property2="p2" data-conf-property3="p3"</div>

I want to create an object consisting of attributes data-conf-*

var conf = $(".class").data() <br>

I tried the above, but it consists of all the attributes that I do not need in accordance with my requirement.

var conf = $(".class").data("conf-*") - this one also not working
+4
source share
4 answers

One way is to create your own plugin.

This takes a regular expression to compare with the property: -

$.fn.ddata = function(regex) {
  var objs = [];
  this.each(function() {
    var obj = {};
    for (var prop in this.dataset)
      if (regex.test(prop))
        obj[prop] = this.dataset[prop];
    objs.push(obj);
  });
  return objs;
};

var conf = $('.class').ddata(/^conf/);

console.log(conf);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="class" data-mark-comp="comp1" data-conf-property1="p1" data-conf-property2="p2" data-conf-property3="p3"></div>
Run codeHide result
+1
source

You can iterate over all the elements that are part of the div .classand create an array of attributes for the relevant entries using:

  var conf= [];
  $(".class").each(function() {
    $.each(this.attributes, function() {
      if (this.name.substring(0, 5)=='data-') {          
        conf[this.name.substring(5)]= this.value;
      }
    });
  });

Here's the fiddle above with comments.

BenG .

0

, data:

<div class="class" data-conf="{ property1: 'p1', property2: 'p2' }">

:

data ( '{') ( '['), jQuery.parseJSON ; JSON, . JavaScript, .

, .

0

:

var data = $(".class").data();
var conf = {};
$.each(data, function(key, value) {
  if(key.startsWith("conf")) conf[key]=value;
});
console.log(conf); // just for verification -- comment this line afterwards
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class" data-mark-comp="comp1" data-conf-property1="p1" data-conf-property2="p2" data-conf-property3="p3">
</div>
Hide result
0

Source: https://habr.com/ru/post/1659423/


All Articles