-2
<p id="getMessage" data-sid="158">
  <strong>Name</strong> : Rahul Kumar<br>
  <strong>Total </strong> : 25<br>
</p>

This is my dynamically generated HTML using jQuery

Now this is stable and fix

I executed several commands in Consol and found these results

$('#getMessage').attr('data-sid');
"158"

This is as expected.

But when I execute this

$('#getMessage').data('sid');
160

It shows 160, it should be 158 right ?

I used $('#getMessage').attr('data-sid', result.studentDetails.SID); to set it.

Rahul Kumar
  • 2,184
  • 3
  • 24
  • 46

3 Answers3

3

.attr will read the actual attribute.

.data will read the current value of that data item. If you have code which has changed the value (ie, $('#getMessage').data('sid',160)) that will be the current value.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

The data() function stores data to a specific element

Store arbitrary data associated with the specified element and/or return the value that was set.

jQuery.data($('#element'), data);

On the other hand, attr() gets or sets attributes form the element.

$('div').attr('data-test', 'test');

<div data-test="test"></div>
kapantzak
  • 11,610
  • 4
  • 39
  • 61
0

as requested a working example..., notice that i can change the value of the data attribute without changing the actual attribute

console.log($('#getMessage').attr('data-sid'));
console.log($('#getMessage').data('sid'));

$('#getMessage').data('sid', 160);

console.log($('#getMessage').attr('data-sid'));
console.log($('#getMessage').data('sid'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="getMessage" data-sid="158">
  <strong>Name</strong> : Rahul Kumar
  <br>
  <strong>Total </strong> : 25
  <br>
</p>
WalksAway
  • 2,769
  • 2
  • 20
  • 42