0

How do I set a data attribute with native js so it is picked up with jquery? I have tried using setAttribute, but that only works for the first occasion an any updates aren't picked up:

var iframeHolder = document.getElementById('test');
iframeHolder.setAttribute('data-test', 5);

var $iframe = $('#test');

console.log($iframe.data('test'));

iframeHolder.setAttribute('data-test', 6); // this doesn't seem to update the underlying data attribute

console.log($iframe.data('test'));

iframeHolder.dataset.test = 6;  // neither does this

console.log($iframe.data('test'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">inspect to see attribute updates</div>

Please note, I need to use native js as it is in an iframe that doesn't use jquery (but sets the data attribute in the parent window which does use jquery)

Pete
  • 57,112
  • 28
  • 117
  • 166
  • 2
    jQuery's `data()` method works with an internal cache. If you use a method *other than* the setter of `data()` to set the value, jQuery won't update its cache and will retain the old value. To work around this either 1) *always* use `data()` as the getter/setter or 2) use `attr()` in jQuery to get the value from the DOM (which is slightly slower) - in this case: `console.log($iframe.attr('data-test'));` – Rory McCrossan Sep 22 '21 at 10:59
  • 1
    ah ok thanks, will have to use `.attr` then – Pete Sep 22 '21 at 11:01

0 Answers0