Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

365
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda