How to store arbitrary data for some HTML tags
To quickly store arbitrary data in an HTML tag, use HTML5's data-*
attributes. Assign any custom data like this: data-detail="info"
directly in your HTML tag.
Example:
Retrieve the data with JavaScript:
Consider server-side generation of data attributes for increased reliability and extensibility.
For JavaScript interaction with data, you might just fall in love with jQuery’s .data()
methods:
Sorry, href
and custom JavaScript objects, you're not invited to this party! They can make your code messy and harder to maintain.
Best practices for storing data in HTML
Using JSON for structured data
For complex or structured data, JSON is your new best friend.
Retrieve the JSON data safely without eval()
, which can turn into a security hole big enough to drive a truck through:
Using JavaScript properties
When data-*
attributes won’t cut it, JavaScript properties could come to your rescue:
It's worth noting that using JavaScript properties for data storage is more like hidden compartments in a car - handy for internal use, but might not be the best idea for showing off your ride.
The trade-offs
Each of these storage methods comes with its own set of pros and cons:
data-*
attributes: Highly versatile and standard. Could bloat HTML if overused.- JSON: Ideal for structured data. Ensure proper validation and formatting for smooth retrieval.
- JavaScript properties: Simple to use but less maintainable as it's separated from the HTML.
Cross-browser compatibility
While data-*
attributes are supported in most modern browsers, their usage in XHTML mode could be misleading as they might get ignored. Always test your code across various browsers and document types.
Keeping your data accessible is important. Note that crucial data mustn't only be readable by JavaScript as this could create accessibility issues.
Stay organized! Avoid clutter by grouping related data attributes together.
Was this article helpful?