I have a script that uses the “data-” type to store info inside an html element. E.G
<div class="My-Widget commentsandrating" data-XYZ="MCAN"></div>
<div class="My-Widget rating" data-XYZ="MCAN"></div>
<div class="My-Widget comments" data-XYZ="MCAN"></div>
some of these will be in the page with the data-XYZ and some as follows:
<div class="My-Widget commentsandrating"></div>
<div class="My-Widget rating"></div>
<div class="My-Widget comments"></div>
I am trying to add the data-xyz to the html.
For all browsers I use the following function
item.setAttribute('data-XYZ', queryString2);
and it works for every browser except for IE ..
I tried using jQuery
jQuery.data(item, 'XYZ', queryString2);
What should i use to set this instead..
Thanks for the help…
Both of the answers are right, but I think they missed to explain what the code does.
In your case, you have two options:
$('element').data('key', 'value'). This will attach data to your DOM element. You can then retrieve it via$('element').data('key')$('element').attr('key','value')and then retrieve it with$('element').attr('key').Although you’re doing the same thing, both methods are different in how you achieve it.
For instance, using
datagives you more choices – you can store whatever you want including JSON and Array data. With$('element').attr('key','value'), you can only store a string.Depending on your choice: