HTML Data Attributes

HTML Data-* Global Attributes

A data*- Global Attribute are custom data attributes used to store custom data (or metadata) private to the page and exchange it with JavaScript. This can occur without any Ajax call or server-side database query.

This was created in HTML 5 to prevent the need to use class or rel for this purpose.

They can be used in a variey of ways:

  • With JavaScript (in a variety of ways) to create interactivity
  • With CSS for styliong

To create data*- attribute thye should beging with data- and use lowercase letters. The data stored in these attributes should also be strings.


Example: HTML Data Attributes

This code creates an interactive, clickable glossary of terms in HTML and JavaScript.


	<head>
		<meta charset="UTF-8">
		<title>HTML Data Attributes</title>
		<script>
		function showDetails(term) {
		  var definition = term.getAttribute("data-desciption");
		  alert(term.innerHTML + definition);
		}
		</script>
	</head>
	<body>

	<h1>Client, Server, Networking Definitions</h1>

	<p>Click on a term to see definition:</p>

	<ul>
	  <li onclick="showDetails(this)" id="access list" data-desciption=" - a list kept by routers to control access to or from the router for a number of services. For example, the list can prevent packets with a certain IP address from leaving a particular interface on the router.">Access List</li>
	  <li onclick="showDetails(this)" id="ANSI" data-desciption=" - American National Standards Institute. The principle group in the US. for defining standards.">ANSI</li>  
	  <li onclick="showDetails(this)" id="ARPANET" data-desciption=" - Advanced Research Projects Agency Network. Landmark packet-switching network established in 1969.">ARPANET</li>  
	  <li onclick="showDetails(this)" id="FTP" data-desciption=" - File Transfer Protocol.">FTP</li>  
	</ul>
	

Run it now


Example: Data Attributes and Styling


	<style>
	li[data-type='individual'] {
		background: #cce6ff;
	}
	li[data-type='corporate'] {
		background: #ffd1b3;
	}
	</style>
	</head>
	<body>

	<h1>Customers</h1>

	<p>Click on a term to see definition:</p>

	<ul>
		<li data-type="individual" data-zipcode="48201">Mary Jones, 91911 Oak Street, Detroit, MI
		<li data-type="individual" data-zipcode="90009">Louis Chavez, 23883 Vine Court, Los Angeles, CA
		<li data-type="corporate" data-zipcode="10009">CS Schipping, 3934 15th Street, New York, NY
	</ul>
	

Run it now


Example: Accesing Data Atttributes via JavaScript getElementById and getAttribute


	<body>
	<div id='smith-makery-orders' data-quantity='125'></div>

	<script>
	var customer = document.getElementById('smith-makery-orders');
	var quantity = customer.getAttribute('data-quantity'); 

	document.write("

Quantity: " + quantity + "

"); </script> </body>

Run it now