Major difficulty in applications is storing a reference to some extra bit of data that is not currently displayed.
For example:
On twitter there is a username. Clicking on that username will bring up more information about the user. When the page first loads that information is not currently loaded to the application. Somehow the application knows who the user is and is able to, with ease, look up extra information that’s not visible by storing some extra information inside of the markup that you don’t currently see.
Here’s a problem
A few ways to
Classes
IDs
Custom attributes
Classes
We can get the class on any DOM element with the .className property. Can be useful when you want to run code whenever only a specific type of element is clicked.
IDs
We can also use IDs to run code based on precisely what was clicked. To get the ID of an DOM element, one would use .getAttribute('id')
Here is an example that gets us closer to a solution to our gourd problem.
Custom attributes
The ID’s got us close, but it would be a lot of work to add a separete clause for each index in our array. It would be much easier if the dom elements themselves knew which array index they were linked to. We can get to that with a custom attribute.
These are attribues that are not used by HTML or for normal markup purposes, but instead work as ‘extra information’ associated with the DOM element. Sometimes prepended with a “data-“ to mark that it is associated data with the element.
Here is an example, making our gourds a bit easier to work with.
Note the data-index attribute in the gourd tags, set to their respective indicies in the extra data array. When one of the gourds is clicked, we get its data-index attribute, and access the data from the array using it.