Search code examples
jqueryhtmlcustom-data-attribute

How to set data attributes in HTML elements


I have a div with an attribute data-myval = "10". I want to update its value; wouldn't it change if I use div.data('myval',20)? Do I need to use div.attr('data-myval','20') only?

Am I getting confused between HTML5 and jQuery? Please advise. Thanks!

EDIT: Updated div.data('myval')=20 to div.data('myval',20), but still the HTML is not updating.


Solution

  • HTML

    <div id="mydiv" data-myval="10"></div>
    

    JS

    var a = $('#mydiv').data('myval'); //getter
    
    $('#mydiv').data('myval',20); //setter
    

    Demo

    Reference

    From the reference:

    jQuery itself uses the .data() method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

    It should be noted that jQuery's data() doesn't change the data attribute in HTML.

    So, if you need to change the data attribute in HTML, you should use .attr() instead.

    HTML

    <div id="outer">
        <div id="mydiv" data-myval="10"></div>
    </div>
    

    ​jQuery:

    alert($('#outer').html());   // alerts <div id="mydiv" data-myval="10"> </div>
    var a = $('#mydiv').data('myval'); //getter
    $('#mydiv').attr("data-myval","20"); //setter
    alert($('#outer').html());   //alerts <div id="mydiv" data-myval="20"> </div>
    

    See this demo