• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Use jQuery’s data() method to store data in the DOM

Use jQuery’s data() method to store data in the DOM

jQuery has a .data() method for storing data in the DOM should you need to for one reason or other. This is preferable to storing data in some other attribute such as "rel" or "alt" which is often seen in tutorials and examples on blogs.

For example if you had a elements with the id "foo" and "bar" you could set data with a name of "fruit" to "orange" for #foo and "banana" for #bar like so:

$('#foo').data('fruit', 'apple');
$('#bar').data('fruit', 'banana');

To fetch the value at a later time call the .data() method just passing in the name like so, where the value is displayed in an alert dialog:

alert( $('#foo').data('fruit') );

If you don’t want to assign the data to a particular element you could always assign it to the body instead:

$('body').data('fruit', 'orange');
alert( $('body').data('fruit') );

Check Out These Related posts:

  1. Ordering by specific field values with MySQL
  2. Load JSON data with jQuery and PHP – Radio Buttons
  3. Load JSON data with jQuery, PHP and MySQL
  4. Example table for MySQL

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap