Get length of all data attributes of element, but dynamically

This code works perfect:

attributes = $("#testForm").data();
console.log(attributes);
console.log(Object.keys(attributes).length);

but only one time, when I dynamically added additional data attributes onclick event, it shows same value. I know that .data() is caches somehow, but how to handle it dynamically

Example:

<form id="testForm" data-id="33" data-size="45">

When I call the code above, it returns 2, but when I added more data attributes, like:

<form id="testForm" data-id="33" data-size="45" data-color="red" data-activity"1">

Code above still returns 2.

$(function ($) {
    attributes = $("#testForm").data();
    console.log(attributes);
    console.log(Object.keys(attributes).length);
    
   $('#testButton').on('click', function () {
     $("#testForm").attr( 'data-size' , 'test' );
     $("#testForm").attr( 'data-use' , 'test' );
      attributes = $("#testForm").data();
      console.log(attributes);
      console.log(Object.keys(attributes).length);
   });
 
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="filter-body" id="testForm" data-length="1">
          <button id="testButton">test<button>
        </form>

getAttribute() and attr() require specific data-attribute name, in my case I will have 10,15 or more data-attributes of element, with different name, so I can pass specific name, I'm looking to get length of all of them, but dynamically.


The data method only reads the values of custom data attributes on first invocation, as mentioned in the docs. So either add your additional data using the data method (then jQuery will handle storage internally), or, if you need them to be actual custom data attributes, use HTMLElement.dataset instead of jQuery's data method.

That is a DOMStringMap, which does not appear to have any length or size properties - so you will have to loop over all the entries, and count them while doing so. https://stackoverflow.com/a/43021996/1427878 shows how to loop over them with a simple for-in loop.