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

239
Views
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 answers
Answer question

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 Report

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 Report

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 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!