Introduction to JQUERY - Adding and Retrieving with the JQUERY data() Method

Guest Posts Paolo Nikko Nuñal

With the introduction with HTML 5 there are many new features being added and one of which is the custom attribute that you can attach to an element. In this tutorial you are going to learn on how you can add a custom "data" to any HTML element of your choosing. This is especially important if you are planning on placing custom data on element with the JQUERY data() method.

Return Data from an Element



NAME - It will specify the name of the data to be retrieve.If there is no name being stored, this method will return all stored data found on the object.

Add Data to an Element



NAME - (REQUIRED) - The name of the data to be set.

VALUE - (REQUIRED) - The value of the data to be set.

In this example you will learn how to add data, and retrieve the data of a specified HTML element.

<script src="">
        $("#section").data("name", "John Doe");
<button type="button" id="btn-attach">Attach Data</button><br>
<button type="button" id="btn-get">Retrieve Data</button>
<div id="section"></div>

When you click on the "Attach" button, it will select the element with the id "section" and in our example, we have a div having that name. After which, it will then placed a data attribute called "name" or "data-name" with the string value "John Doe".

data("name","John Doe") =  data-[name]=["John Doe"]

Once you click on the "Retrieve" button, what happens here it will look for the id that matches your selector. In our case we have the id ="section" that matches our example div. After which, we get the value of the data depending on the name of the data attribute. In our case we have the "data-name".

That's it, this is how you can add and retrieve any data attribute using the data() method in JQUERY.