jQuery Tutorial Tutorials - jQuery .data() method

jQuery .data() method

The .data() method in jQuery is used to store any data associated with the matched element and/or returns the value that stored for the first matched element.

jQuery .data() method Syntax

.data(key,value)
.data(obj)
.data(key)
.data()
Parameter Type Description
key String name the piece of data to set
value Anything The new data value
obj Object An object of key-value pairs of data to add or update

.data(key,value)

Store datavalue with the matched element. the key is for retrieving.

example

Set values for the first div element

var $firstDiv = $('div:eq(0)');
$firstDiv.data('foo',30)
$firstDiv.data('bar',{duration:10, state: 'play'});

.data(obj)

Store obj value with the matched element.

example

set an array data for the first div element.

$('div:eq(0)').data( { blah : [1,2,3,4] });

.data(key)

Get the data-* data of the matched element or value specified by key which setted by data() before.

example

Get the data associated with the first matched element.

$('div:eq(0)').data('test') // undefined
$('div:eq(0)').data('foo'); // 30
// html <div data-target="Lautturi"></div>
$('div:eq(1)').data('target');

.data()

Get all data-* data of the matched element or all values setted by data().

var elem = document.createElement( "p" );
$( elem ).data( "test" ); // undefined
$( elem ).data(); // {}
 
$( elem ).data( "test", 3 );
$( elem ).data( "test" ); // 3
$( elem ).data(); // { test: 3 }

jQuery .data() method Example

Try now

Date:2019-08-20 16:14:25 From:www.Lautturi.com author:Lautturi