Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
be well Avatar asked Mar 16 '17 09:03

be well


1 Answers

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.

like image 200
Rory McCrossan Avatar answered Sep 28 '22 12:09

Rory McCrossan