Change html data attribute value

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).data('bla') );
            $(this).attr('data-bla', "2");  
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

So, I need change data-bla value from "1" to "2", but as you can see, value not updated and every click on button, alerts default value "1".

What did I do wrong?

Asked By: Oto Shavadze
||

Answer #1:

data() is not an accessor function for data-* attributes. It's an accessor for jQuery's data cache for the element, which is only initialized from data-* attributes.

If you want to read the data-bla attribute's value, use attr("data-bla"), not data("bla"). If you want to set the bla data item, use data("bla", newValue), not attr("data-bla", newValue).

E.g., use attr() for both get and set, or use data() for both get and set, but don't mix them, because they manage different things.

Using attr():

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).attr('data-bla') );
            $(this).attr('data-bla', "2");  
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

Using data():

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).data('bla') );
            $(this).data('bla', "2");  
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

Answered By: T.J. Crowder

Answer #2:

The attr() method just update the attribute which is visible in the element. To store the data in right way you need to use data() method with second argument as the value.

$(document).ready(function() {
  $("#bla").on("click", function() {
    alert($(this).data('bla'));
    $(this).data('bla', "2");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

Refer : jQuery Data vs Attr?

Answered By: Pranav C Balan

Answer #3:

If you check for .data('bla'), you should also change that one ;-)

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).data('bla') );
            $(this).data('bla', "2");  
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

Answered By: DarkLegend
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles