Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data-attribute jquery vs javascript

I have a custom data-attribute set by default:

data-equipment="0"

If i change it with jquery using .data()

$(this).data("equipment", 10)

and then use the getAttribute()

this.getAttribute("data-equipment")

i get the old value (0) and not the new one (10). But if i use

$(this).data("equipment") i get the new value (10).

Is this supposed to work like this or am i missing something?

Thanks!

like image 583
pedroto Avatar asked Aug 07 '13 15:08

pedroto


People also ask

How get data attribute in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).

How do I find data attributes?

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.

What is data attribute in JavaScript?

The data-* attribute gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

How can get li id value in jQuery?

on('click', function (e) { var id = $(e. target). attr('id'); console. log(id); });


1 Answers

.data() doesn't operate on data attributes but in internal jQuery cache. Initially if no cache record is found, the data is read from a corresponding data- attribute if one exists, but that is the end of their co-operation.

If it operated on attributes, it would be useless for its purpose because attribute values must be strings.

like image 182
Esailija Avatar answered Sep 20 '22 17:09

Esailija