jQuery : Associate data with dom element

21 / Sep / 2012 by Amit Jain 1 comments

There are times when we need to associate data with the DOM element say td, li, div etc. I used to sometimes provide attribute ‘rel’ to html tag, then access it using $(‘divId’).attr(‘rel’). This worked when we want to associate only one property, but doesn’t work so well when there are multiple properties to be associated with the same element. And I personally never liked this approach as there was no name given to the type of data attached.

Recently I found that jQuery provides a method called data(), which can be used to associate multiple data with the same element. Lets take a look at the example given below :

[js]
<div id=’studentDetail’ data-age=’24’ data-name=’amit’>
……
</div>

<script type="text/javascript">

$(‘#studentDetail’).data(‘age’) // output : 24
$(‘#studentDetail’).data(‘name’) // output : amit

$(‘#studentDetail’).data(‘course’, ‘MCA’) // Associate new data to the element
$(‘#studentDetail’).data(‘course’) // output : MCA

$(‘#studentDetail’).data(‘course-duration’, ‘3 Years’) // Associate new data to the element
$(‘#studentDetail’).data(‘course-duration’) // output : 3 Years
</script>

[/js]

Cheers!
~~Amit Jain~~
amit@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Tag -

data dom jquery

comments (1 “jQuery : Associate data with dom element”)

Leave a Reply

Your email address will not be published. Required fields are marked *