1

I have a global data holder element like that:

<div class="data-holder" data-id="" data-type="" data-age=""></div>

(It's longer but it's enough to get the idea)

Now I want to make a short function which will add values to those data attributes from other elements.

So for example if the user clicks an element with data-type="381" it will add 381 to the global "data-holder" element in the data-type attribute. (each element has only one data attribute (data-type, or data-age and so...).

So I found this global function to remove all attributes from an element:

$.each($(this).data(), function (key) {
    // Because each key is in camelCase,
    // we need to convert it to kabob-case and store it in attr.
    var attr = 'data-' + key.replace(/([A-Z])/g, '-$1').toLowerCase(); 
    // Remove the attribute.
    $(this).removeAttr(attr);
});

And I thought if I will use it like that:

$.each($(this).data(), function (key) {
    // Because each key is in camelCase,
    // we need to convert it to kabob-case and store it in attr.
    var attr = 'data-' + key.replace(/([A-Z])/g, '-$1').toLowerCase(); 
    // Remove the attribute.
    // $(this).removeAttr(attr);
    alert($(this).attr(attr));    
});

I will get the current element's attribute value. but I get as "undefined".

Any ideas? Thanks!

Ajith
  • 2,476
  • 2
  • 17
  • 38
mondi
  • 529
  • 3
  • 16

1 Answers1

0

First, the function you've found doesn't remove data attributes but changes the way the attributes are written, which is not what you're looking for.

Also, I would advice putting an ID "data-holder" to your DIV instead of a class if it is meant to be global. It will help make you sure only you have one in your page (which would change the example for $('#data-holder') ).

As for the code, here is what I would recommend. I've added a click event adapted for the DIV containing the data you want to click on to update .data-holder.

Example DIV:

<div class="element-with-data" data-id="24124" data-type="something" data-age="25">

In jQuery,

$('.element-with-data').on('click', function(evt){
    var data = $(evt.target).data();
    $.each(data, function (i) {
         $('.data-holder').attr("data-" + i, data[i]);
    });
}); 

(Inspired from this answer: https://stackoverflow.com/a/24059528/8452283.)

cetteSara
  • 331
  • 3
  • 5
  • `data[i]` is undefined. – mondi Aug 11 '20 at 12:41
  • @mondi $('.element-with-data').on('click' ... must correspond to your DIVs. I put ".element-with-data" as a class example since I don't know what you DIVs look like. You can add "console.log(evt.target, data);" inside the $.each to see if you caught the right elements. – cetteSara Aug 11 '20 at 14:23