Reputation: 2539
I have this fiddle. In it I try to set a data attribute on a button. Doesn't work.
$("button").data("test", "tested");
using .prop("date-test", "tested):
does not work. It will work if I use .attr()
. Is this special to buttons in jQuery?
Upvotes: 2
Views: 136
Reputation: 24965
Calling attr(key)
will get the attribute on the element. The value will always be a String, if it exists.
Calling attr(key, value)
will set the attribute on the element, and will not update any jQuery cache.
Calling data(key)
will get the data element out of the jQuery cache. If it is not found, it will get the value from the attribute and cache it for future requests for it. It will also try to auto parse the string into whatever type it can, so the value will not always be a String.
Calling data(key, value)
will set the value in the cache, and will not update the attribute on the element.
var $button = $('button');
//set the attribute on the element
$button.attr('data-test1', 'hi');
//First time call with attr get, value will be correct
//First time call with data get, value will be correct as it falls back to getting the attr value
console.log( 'Set with attr =>', $button.attr('data-test1'), $button.data('test1'));
//set the data value in the jQuery cache. does not change any attribute
$button.data('test2', 'hi2');
//First time call with attr get, value will be undefined
//First time call with data get, value will be correct
console.log( 'Set with data =>', $button.attr('data-test2'), $button.data('test2'));
//modify the attr after data() has already been called
$button.attr('data-test1', 'new value');
//Second time call with attr get, value will be correct
//Second time call with data get, value will be incorrect as it has the previously cached value that is not updated with attr()
console.log( 'Set with attr =>', $button.attr('data-test1'), $button.data('test1'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Blah</button>
Upvotes: 2