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

246
Vistas
Getting a data attribute after dynamic change

I have a simple setup with an attribute 'data-id' attached to the element:

<div class='row' data-id='1'>

If I call alert($(.row).data(id)); I will get my id 1. Next thing I change this id manually or via another script to, say, 2:

<div class='row' data-id='2'>

and now if I call alert($(.row).data(id)); I still will get 1 instead of 2.

However, if I change method .data() to attr('data-id') the result gonna be 2.

What is the reason of such behavior?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

The reason is because jQuery stores all data attribute key/value pairs in an object, separate from the DOM. The data() method reads from this object.

When you update the data attribute using attr() you update the DOM only, hence the data() method reads the old value from the in memory object.

For this reason it's always best to use data() as both the setter and getter.

over 4 years ago · Santiago Trujillo Denunciar

0

$(.row).data('id', 'your new value')

Use above setter method to update your data-id value

After when you get $('.row').data('id') then you get your updated value

over 4 years ago · Santiago Trujillo Denunciar

0

For Set and Get attribute use data() instead of attr()

<div class='row' data-id='1'>

 

//set attr
$(.row).data("id","NEW_VAL");

//get attr
$(.row).data("id");
over 4 years ago · Santiago Trujillo 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