Rahul Kumar Rahul Kumar - 4 months ago 8
Javascript Question

Different results by attr and data

<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.

Answer

.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.