1 1 Vote

jQuery: Read and Change Data Attribute Value

Tutorial by Stefan Trost | 27/05/2015 at 20:52

In this tutorial, I would like to show you how to read out and modify the data attribute value of an arbitrary HTML element using JavaScript and jQuery. As an example, we would like to use the following HTML.

<div id="mydiv" data-a="1" data-b="2"></div>

As you can see, this is a DIV with the ID "mydiv" having assigned 2 data attributes. In detail, that is the attribute "data-a" with the value 1 and "data-b" with the value 2.

Read Data Attribute Values

When reading out data attributes, jQuery is helping us with offering the method .data(). Let us have a look at an example.

var a = $("#mydiv").data("a");
var b = $("#mydiv").data("b");

var c = a + b;


Here, we are reading out both data attributes from the DIV, we are summing up the values and showing an alert containing the result.

Concretely, we are using the selector $("#mydiv") in order to select the DIV. Afterwards, we are using .data("a") and .data("b") to get the values of the attributes. We are storing them in the variables a and b, saving the sum in c and outputting c with alert().

As you can see, when using .data(), we do not have to write "data-a" or "data-b". It is sufficient to write "a" and "b". 

Write Data Attribute Values

When passing a second parameter to .data(), this parameter is written to the corresponding data attribute. Here is a small example.

var a_new = 10;

$("#mydiv").data("a", a_new);
$("#mydiv").data("b", "test");

Again, we are using the selector $("#mydiv") in order to select the DIV. After that, we are setting the data attribute "a" to a variable we have defined before and we are setting "b" to a string, we have specified directly.


About the Author

Avatar AuthorYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile | Message


Related Topics

jQuery: Change Image
Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own articles on askingbox.com. How to do.