Data Attributes In HTML5
HTML5 application developers can create custom attributes to save data. Each HTML element can store multiple data attributes. The HTML5 data attribute feature works in all current major browsers.
The data attribute name must be contain the prefix “data-“. The data value of each attribute can be set and retrieved using JavaScript.
This tutorial uses HTML5 custom data attributes.
- Tools are required:
- Text editor.
- Folder for web server.
- Browser to view output.
HTML5-Data-Attributes.html File
<!-- HTML5-Data-Attributes.html Copyright 2013 edward <http://Ojambo.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --> <!DOCTYPE html> <html xml:lang="en" lang="en"> <head> <title>Ojambo.com HTML5</title> <meta charset="utf-8" /> <script type="text/JavaScript"> function changeContent(){ var ojamboWeb = document.getElementById('ojamboWeb'); var dataOjamboWeb = ojamboWeb.getAttribute('data-ojambo-web'); var ojamboUrl = document.getElementById('ojamboUrl'); ojamboUrl.innerHTML = dataOjamboWeb; } </script> </head> <body> <div id="content"> <p>Main content</p> <p id="ojamboWeb" data-ojambo-web="http://ojambo.com">Contains data</p> <h3 id="ojamboUrl">Will be changed</h3> <p><button type="button" onclick="changeContent();">Change</button></p> </div> </body> </html>
JavaScript can obtain and set attribute values using “getAttribute” and “setAttribute” methods respectively. Data attributes require the prefix “data-” A unique identifier was created in order to obtain a specific data attribute.
The JavaScript function “changeContent” is called when the button is pressed. The data attribute is used to change the HTML content of the h3 tag.
How to Use:
- Open Browser
- Press the change button.
- Observe the changed content.
Demonstration:
Ojambo.com HTML5 Data Attribute Tutorial
Conclusion:
Web application developers can use HTML5 to create custom data attributes. Each element can store unique data using a custom data attribute prefix of “data-“.
A unique identifier can be used in order to target specific elements. Data attributes can be accessed and created with JavaScript.
- Recommendations:
- Set original data attributes without JavaScript.
- Use elaborate custom data attributes.
- Use unique identifiers to target specific DOM elements.
- References:
- Ojambo.com Lightweight Programming Editors.