Attributes
Getting started with ... is a concise series introducing you to the practicalities of web development. You'll set up the tools you need to construct a simple webpage and publish your own simple code.
We've only touched the surface of HTML global attributes. There are even more attributes that apply to only one or a limited set of elements. Even with hundreds of defined attributes, you may have a need for an attribute that isn't in the specification. HTML has you covered.
You can create any custom attribute you want by adding the data-
prefix. You can name your attribute anything that starts with data-
followed by any lowercase series of characters that don't start with xml
and don't contain a colon (:
).
While HTML is forgiving and won't break if you create unsupported attributes that don't start with data
, or even if you start
your custom attribute with xml
or include a :
, there are benefits to creating valid custom attributes that begin with data-
.
With custom data attributes you know that you aren't accidentally using an existing attribute name. Custom data attributes are future-proof.
While browsers won't implement default behaviors for any specific data-
prefixed attribute, there is a built-in dataset API
to iterate through your custom attributes. Custom properties are an excellent way of communicating application-specific information
via JavaScript. Add custom attributes to elements in the form of data-name
and access these through the DOM using dataset[name]
on the element in question.
<blockquote data-machine-learning="workshop"
data-first-name="Blendan" data-last-name="Smooth"
data-formerly="Margarita Maker" data-aspiring="Load Balancer"
data-year-graduated="2022">
HAL and EVE could teach a fan to blow hot air.
</blockquote>
You can use getAttribute()
using the full attribute name, or you can take advantage of the simpler dataset
property.
el.dataset[machineLearning]; // workshop
e.dataset.machineLearning; // workshop
The dataset
property returns a DOMStringMap
object of each element's data-
attributes. There are several custom attributes
on the <blockquote>
. The dataset property means you don't need to know what those custom attributes are in order to access their
names and values:
for (let key in el.dataset) {
customObject[key] = el.dataset[key];
}
The attributes in this article are global, meaning they can be applied to any HTML element (though they don't all have an impact on
those elements). Up next, we take a look at the two attributes from the intro image that we didn't address—target
and href
—and
several other element-specific attributes as we take a deeper look into links.