JQuery data selector not updating with .data

Basically, if I upload a div to a page with the data-test attribute and change its value using jquery .data('test') I can no longer select an element using $('div[data-test="newValue"]')

 var howMany = $('.t[data-test="test"]').length; $('.result').html('start there are ' + howMany + ' divs with data "test"<br /><br />'); setTimeout(function() { $('#one, #three').data('test', 'changed'); }, 500); setTimeout(function() { var test = $('.t[data-test="test"]').length, changed = $('.t[data-test="changed"]').length; $('.result').append('there are ' + test + ' divs still with data "test"<br /><br />there are ' + changed + ' divs still with data "changed"<br /><br />'); }, 1000); setTimeout(function() { $('.t').each(function() { $('.result').append('div #' + $(this).attr('id') + ' has the test data of: ' + $(this).data('test') + '<br /><br />'); }); }, 1500); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="t" id="one" data-test="test">1</div> <div class="t" id="two" data-test="test">2</div> <div class="t" id="three" data-test="test">3</div> <div class="t" id="four" data-test="test">4</div> <div class="result"></div> 
+60
jquery html html5 jquery-selectors
Mar 19 '12 at 9:59
source share
2 answers

jQuery.data () is initially populated with values ​​from the data- attributes, but during installation it only stores the new value in memory. It does not change the attribute in the DOM. To change an attribute, you must use:

 $('#one, #three').attr('data-test', 'changed'); 

Docs are at http://api.jquery.com/jQuery.data/

+140
Mar 19 '12 at 10:03
source share

This is because .data() uses a special cache object inside jQuery to store data (in fact, you can save the storage object or complex data hints) if you check all the attributes unchanged. If you want to change the attribute, use attr()

+10
Mar 19 2018-12-12T00:
source share



All Articles