Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

360
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!