[jquery] 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.

This question is related to jquery html custom-data-attribute

The answer is


Vanilla Javascript solution

HTML

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

JavaScript:

  • Using DOM's getAttribute() property

     var brand = mydiv.getAttribute("data-myval")//returns "10"
     mydiv.setAttribute("data-myval", "20")      //changes "data-myval" to "20"
     mydiv.removeAttribute("data-myval")         //removes "data-myval" attribute entirely
    
  • Using JavaScript's dataset property

    var myval = mydiv.dataset.myval     //returns "10"
    mydiv.dataset.myval = '20'          //changes "data-myval" to "20"
    mydiv.dataset.myval = null          //removes "data-myval" attribute
    

[jQuery] .data() vs .attr() vs .extend()

The jQuery method .data() updates an internal object managed by jQuery through the use of the method, if I'm correct.

If you'd like to update your data-attributes with some spread, use --

$('body').attr({ 'data-test': 'text' });

-- otherwise, $('body').attr('data-test', 'text'); will work just fine.

Another way you could accomplish this is using --

$.extend( $('body')[0].dataset, { datum: true } );

-- which restricts any attribute change to HTMLElement.prototype.dataset, not any additional HTMLElement.prototype.attributes.


Another way to set the data- attribute is using the dataset property.

<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>

const el = document.querySelector('#user');

// el.id == 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'johndoe'
// el.dataset.dateOfBirth === ''

// set the data attribute
el.dataset.dateOfBirth = '1960-10-03'; 
// Result: el.dataset.dateOfBirth === 1960-10-03

delete el.dataset.dateOfBirth;
// Result: el.dataset.dateOfBirth === undefined

// 'someDataAttr' in el.dataset === false
el.dataset.someDataAttr = 'mydata';
// Result: 'someDataAttr' in el.dataset === true

You can also use the following attr thing;

HTML

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

Script

 $('#mydiv').attr('data-myval', 'Undertaker'); // sets 
 $('#mydiv').attr('data-myval'); // gets

OR

$('#mydiv').data('myval'); // gets value
$('#mydiv').data('myval','John Cena'); // sets value

To keep jQuery and the DOM in sync, a simple option may be

$('#mydiv').data('myval',20).attr('data-myval',20);        

Please take note that jQuery .data() is not updated when you change html5 data- attributes with javascript.

If you use jQuery .data() to set data- attributes in HTML elements you better use jQuery .data() to read them. Otherwise there can be inconsistencies if you update the attributes dynamically. For example, see setAttribute(), dataset(), attr() below. Change the value, push the button several times and see the console.

_x000D_
_x000D_
$("#button").on("click", function() {_x000D_
  var field = document.querySelector("#textfield")_x000D_
_x000D_
  switch ($("#method").val()) {_x000D_
    case "setAttribute":_x000D_
      field.setAttribute("data-customval", field.value)_x000D_
      break;_x000D_
    case "dataset":_x000D_
      field.dataset.customval = field.value_x000D_
      break;_x000D_
    case "jQuerydata":_x000D_
      $(field).data("customval", field.value)_x000D_
      break;_x000D_
    case "jQueryattr":_x000D_
      $(field).attr("data-customval", field.value)_x000D_
      break;_x000D_
  }_x000D_
_x000D_
  objValues = {}_x000D_
  objValues['$(field).data("customval")'] = $(field).data("customval")_x000D_
  objValues['$(field).attr("data-customval")'] = $(field).attr("data-customval")_x000D_
  objValues['field.getAttribute("data-customval")'] = field.getAttribute("data-customval")_x000D_
  objValues['field.dataset.customval'] = field.dataset.customval_x000D_
_x000D_
  console.table([objValues])_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<h1>Example</h1>_x000D_
<form>_x000D_
  <input id="textfield" type="text" data-customval="initial">_x000D_
  <br/>_x000D_
  <input type="button" value="Set and show in console.table (F12)" id="button">_x000D_
  <br/>_x000D_
  <select id="method">_x000D_
    <option value="setAttribute">setAttribute</option>_x000D_
    <option value="dataset">dataset</option>_x000D_
    <option value="jQuerydata">jQuery data</option>_x000D_
    <option value="jQueryattr">jQuery attr</option>_x000D_
  </select>_x000D_
  <div id="results"></div>_x000D_
</form>
_x000D_
_x000D_
_x000D_


If you're using jQuery, use .data():

div.data('myval', 20);

You can store arbitrary data with .data(), but you're restricted to just strings when using .attr().


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to custom-data-attribute

How can I get the values of data attributes in JavaScript code? jQuery: get data attribute jQuery find element by data attribute value Using HTML data-attribute to set CSS background-image url Adding data attribute to DOM Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error? How to set data attributes in HTML elements jQuery Data vs Attr? Unable to set data attribute using jQuery Data() API Select elements by attribute in CSS