Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Plugin to allow easy read/write access to HTML5 data- attributes
$.fn.dataset = function(key, value) {
if(value != null) {
if($(this).attr('data-' + key)) {
$(this).attr('data-' + key, value);
return true;
} else {
return false;
} else {
return $(this).attr('data-' + key);

This comment has been minimized.

Copy link
Owner Author

@paulspringett paulspringett commented Jul 21, 2010

Given the initial HTML

<div class="foo" data-length="300" data-color="red">Hello World!</div>

Reading data attributes

$('').dataset('length') => "300"

Writing data attrbiutes

$('').dataset('color', 'green') => true

<div class="foo" data-length="300" data-color="green">Hello World!</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment