yarek yarek - 2 months ago 8
jQuery Question

JQUERY how to set data on html content?

I have a variable s that contains string

'<div>hello world</div>'


(I cannot change the content of s)

I would like to set data on s
I tried:

$(s).data('value', 50);
$($(s)).data('value', 50);


Any idea ?

s = '<div>hello world</div>';
s = $(s).data('value', 50); // works now !!!
console.log($(s).data('value'));

Answer

Your first example ($(s).data('value', 50);) is working fine. You won't see it update in the DOM as jQuery holds data attributes in an internal cache for better performance. You can verify it worked by reading the value back out:

var $div = $('div');

console.log('before: ' + $div.data('value'));
$div.data('value', 50);
console.log('after: ' + $div.data('value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hello world</div>

If you would prefer to update the data-value attribute in the DOM, use attr(), like this:

var $div = $('div');
$div.attr('data-value', 50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hello world</div>

Use the DOM inspector to see the effect of the above code.