Data attribute value updated by jquery is not visible in DOM
Asked Answered
G

2

22

I am updating a data attribute by jQuery, Like:

jQuery('div').data('hidden', 'true');
alert(jQuery('div').data('hidden'));

Data attribute value got changed and returned new value which is true but DOM is still showing the old value which is false.

Guess answered 16/7, 2013 at 3:52 Comment(0)
B
40

When you use .data() to update a data value, it is updating internal object managed by jQuery, so it will not be updated in the data-* attribute

Benniebenning answered 16/7, 2013 at 3:56 Comment(6)
@HowToPlease yes, attr() updates the dom attribute, both of the serves different purposes.Benniebenning
why do you want the element attribute to be updated in the first placeBenniebenning
I was using data attribute for else if, I seen that data is not updating, but when I did alert then it shows the updated value.Guess
I also faced the same problem, using attr() solved the problem. I dont know why jquery managing a object instead of injecting it in the DOM :(Arjun
Is there any noticeable problems that could be encountered by the fact that the added data attributes are not visible in the dom? Jquery finds them just find when you use jquery to search for them.Greenbrier
@Greenbrier no.... it wont show up because jQuery saves it in an internal data structure... not using the native data api.Benniebenning
P
5

I was beating around the bush so badly :( and able to solve the problem. Seams like we can't do achieve this using the jquery data method if the html is dynamic and the data attribute changed later after accessing the first time.

According to jQuery.data()

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

So what I did is, changed it to attr method which won't give you the parsed value for integer, so you have to use '+' operand to convert like:

+ myElement.attr('data-index');

Note: You have to be careful, it will convert the result to NaN if there is any string in the data attr. BTW it's your choice of implementation of the code.

Photocell answered 23/3, 2016 at 10:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.