0

I'm trying to make a function that gets all data-attributes dynamically from an element. For e.g.:

<button id="button" data-key1="title" data-key2="content">Button 1</button>
<button id="changeButtonData">Change data for button 1</button>
$(document).on('click', '#button', function(e){
    e.preventDefault();
    $buttonData = $(this).data();
    console.log($buttonData);
}

$(document).on('click', '#changeButtonData', function(e){
    e.preventDefault();
    //edit existing data-keys value
    $('#button').data('data-key1', 'newtitle');
    //store new data-key on element
    $('#button').data('data-key3', 'new');
}

The problem is, if i click the first button and check the console log, it will show data-key1="title" and data-key2="content"

And if i click the 2nd button afterwards, and click the first button again to fire the console logging again, it won't display the new replaced data-attributes or the new data-tags.

Anyone got an idea how to solve this?

0

1 Answer 1

1

The issue is because when you set the data attribute you should omit the data- prefix, eg: $('#button').data('key3', 'new');. Try this:

$(document).on('click', '#changeButtonData', function (e) {
    e.preventDefault();
    $('#button').data({
        'key1': 'newtitle',
        'key3': 'new'
    });
});

Example fiddle

Sign up to request clarification or add additional context in comments.

5 Comments

Your fiddle doesn't work (I'm on Safari 8) - I was testing this out and had the same idea but I can't seem to get it working.
I just tried it on Safari 8.0.3 for OSX and it worked fine. What makes you say that it did not work? Don't forget that the attributes themselves will not be changed in the DOM - jQuery stores them in an internal cache.
Aha thanks that helps :) I couldnt find that info the docs immediately. Annoying, though.
Yeah, I just edited my previous comment. jQuery does indeed store data attributes in an internal cache for performance benefits - you will see no change in the DOM, this is correct behaviour.
Okay thats the thing then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.