Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@paulspringett
Created July 21, 2010 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulspringett/484515 to your computer and use it in GitHub Desktop.
Save paulspringett/484515 to your computer and use it in GitHub Desktop.
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);
}
};
@paulspringett
Copy link
Author

Given the initial HTML

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

Reading data attributes

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

Writing data attrbiutes

$('div.foo').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