jquery data method

the jquery $.data() method is used to attaches data to , or gets data from matched elements.

attach data to an element.

the data(key,value) method is used to attach arbitrary data associated with the matched elements.

the jquery data method syntax :-

        $( selector ) .data ( keyvalue )
parameterdescription
keyrequired.specifies the key of data to set.
valuerequired.the value of the data to set.

the jquery data(object) method is used to attach arbitrary data associated with the matched elements.object hold the values as (key/value pairs).

the jquery data method syntax :-

       $( selector ) .data ( object )
parameterdescription
objectrequired.specifies an object of key-value pairs of data.

return value from an element

the data(key) method used to retrieve data from a selected element.

the jquery data(key) method syntax :-

       $( selector ) .data ( key )
parameterdescription
keyoptional.specifies name of data to retrieve.

jquery data method example

               <script
                   
                   $(document).ready(function(){
                   
                   $("button:first").click(function(event){
                   
                   $("div").data("name","sandeep kumar nehra");
                   
                     }); 
                     
                   $("button:last").click(function(event){
                   
                   $("div").text("name :-"+$("div").data("name"));
                   
                     alert("my name is"+$("div").data("name"));
                     
                        }); 
                        
                   
                     }); 
                     
              </script>
               

note :- the zero argument .data() method retrieves all of the values as a object(key/value pairs)