Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data attribute value updated by jquery is not visible in DOM

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.

like image 274
user007 Avatar asked Jul 16 '13 03:07

user007


People also ask

How get current data attribute value in jQuery?

$(". delete") will select all elements having that class and . attr("data-id") will give the data-id attribute value of the first element from the set. When the Delete button is clicked, store the value in variable/on Yes button in DOM and use when Yes button is clicked.

Which jQuery DOM method is used to get the attribute value?

The jQuery attr() method is used to get attribute values.

How do I find attributes in Dom?

HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.

What is data() in jQuery?

The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: $(selector). data(para1); Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element.


2 Answers

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

like image 119
Arun P Johny Avatar answered Oct 30 '22 15:10

Arun P Johny


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.

like image 30
Mahavir Avatar answered Oct 30 '22 17:10

Mahavir