Reputation: 13184
I've got div like
<div data-a="aa"> </div>
Then I'm getting its data with:
var data = $("div").data();
And its working fine. Then I'm adding new data like this via data- attribute:
$("div").attr("data-b", "bb");
Then I'm getting data again like
var updatedData = $("div").data();
However, the new value ( data-b
attr with bb
value ) is not there. Why is that? (I want to manage data via data-
attributes)
Using attributes is suitable in my case, so I dont want to use .data("key", "val")
. data-
attributes are valid anyway
Interesting thing is that when I add data- attribute before first call of .data() - it works ok. Is there a way to ignore or 'rebuild' cache of data then? example here
Upvotes: 0
Views: 70
Reputation: 10466
Try using dataset
var article = document.querySelector('#div1'),
updatedData = article.dataset;
Reference JavaScript Access
Upvotes: 0
Reputation: 1539
There are two ways to add data to an element either you can use data() function by jQuery or you can manually add the 'data-attribute'
The issue you're facing is you can always GET as well as SET the data-attribute's value with data() function. But the attribute SET by this function won't be visible in HTML file.
In the below, 'data-c' won't be visible in the HTML file.
<div class='bar' data-a='avalue' data-b='bvalue'></div>
<script>
console.log($( "div" ).data());
$( "div" ).data('c','cvalue');
console.log($( "div" ).data());
</script>
Upvotes: 0
Reputation: 388326
When you use the data()
api, jquery uses an internal private data structure to store the data so the attribute value is not updated.
When you use the data api, there is no need to use the data-
prefix.
So once you use the data api to read the values the attribute values are copied to the internal data structure thereafter any changes done to the attribute will not be reflected in the data api.
Demo: Fiddle
Upvotes: 2
Reputation: 25527
Use .data("key","value")
to set the value
$("div").data("b", "bb");
Also use .data("key")
to get the value
var data = $("div").data("b");
Upvotes: 4