Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

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.

about 4 years ago · Santiago Trujillo Relatório

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

about 4 years ago · Santiago Trujillo Relatório

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");
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda