0

I read this discussion jQuery Data vs Attr? about the difference in usage between $ .data and $ .attr

One of the answers said this

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

I tried to set a value with attr() and then take it with both attr() and date(), but the result is different from what is written.

$(document).on('change', '#sl', function() {
  var selVal = $(this).val();
  $('#txt').removeAttr('data-name');
  $('#txt').attr('data-name', selVal);
  console.log("get by attr " + $('#txt').attr('data-name'));
  console.log("get by data " + $('#txt').data('name')); // get only the first attribute you set
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sl">
      <option value="foo">foo</option>
      <option value="bar">bar</option>
    </select>

<input id="txt">

Can you explain to me if I'm wrong or if I understand what was written?
Thank you

Satpal
  • 132,252
  • 13
  • 159
  • 168
Paolo Rossi
  • 2,490
  • 9
  • 43
  • 70

1 Answers1

1

.data() uses internal cache it only uses the data attribute as the default value only. On performing update operation via .data(key, value) then DOM is not updated. Also on updating .attr(key, value) it will not update the cache.

In short don't mix .attr() and .data()

Satpal
  • 132,252
  • 13
  • 159
  • 168