Custom attributes in html element

Using data attributes

HTML is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.

HTML syntax

The syntax is simple. Any attribute on any element whose attribute name starts with data- is a data attribute. Say you have an article and you want to store some extra information that doesn’t have any visual representation. Just use data attributes for that:

article id="electric-cars" data-columns="3" data-index-number="12314" data-parent="cars">article> 

JavaScript access

Reading the values of these attributes out in JavaScript is also very simple. You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase).

const article = document.querySelector("#electric-cars"); // The following would also work: // const article = document.getElementById("electric-cars") article.dataset.columns; // "3" article.dataset.indexNumber; // "12314" article.dataset.parent; // "cars" 

Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to «5» .

Читайте также:  Фон html голубого цвета

CSS access

Note that, as data attributes are plain HTML attributes, you can even access them from CSS. For example to show the parent data on the article you can use generated content in CSS with the attr() function:

article::before  content: attr(data-parent); > 

You can also use the attribute selectors in CSS to change styles according to the data:

article[data-columns="3"]  width: 400px; > article[data-columns="4"]  width: 600px; > 

You can see all this working together in this JSBin example.

Data attributes can also be stored to contain information that is constantly changing, like scores in a game. Using the CSS selectors and JavaScript access here this allows you to build some nifty effects without having to write your own display routines. See this screencast for an example using generated content and CSS transitions (JSBin example).

Data values are strings. Number values must be quoted in the selector for the styling to take effect.

Issues

Do not store content that should be visible and accessible in data attributes, because assistive technology may not access them. In addition, search crawlers may not index data attributes’ values.

See also

  • This article is adapted from Using data attributes in JavaScript and CSS on hacks.mozilla.org.
  • Custom attributes are also supported in SVG 2; see SVGElement.dataset and data-* for more information.
  • How to use HTML data attributes (Sitepoint)

Found a content problem with this page?

This page was last modified on Jun 30, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Using Custom Attributes in HTML5

Custom attributes are among the most significant additions for HTML5, and can play a major role in semantic Web development. In this tutorial we’ll go through a practical example of creating and accessing HTML5 custom data attributes, including the necessary JavaScript functions.

It was possible before HTML5 to add your own attributes to HTML elements and access them using JavaScript, but if you’ve ever tried it you’ll know you can forget about getting your markup to validate. HTML5 provides the ability to create and use your own element attributes within valid pages.

Create Your HTML5 Document

If you don’t already have one you want to use, copy the following outline into an HTML file:

We will place our elements with custom attributes in the body and the JavaScript functions for accessing them in the head section script area.

Create an Element

Let’s add an element with some simple content and a custom attribute as well as an ID so that we can identify it in JavaScript for demonstration:

As you can see, the custom attribute has the form: “data-*” with a name or names of your choice after the “data-” section. This is the only valid way to use custom attributes in HTML5, so make sure you start your elements this way if you need your pages to validate.

Of course the details of your own projects will dictate whether custom attributes are useful to you, as well as how to go about naming them. This example could be for a retail site with different product categories. The custom attributes allow you to treat elements in particular ways within the JavaScript code for the page, for example when using animated display functions. It’s really only advisable to use custom attributes if there is no standard HTML attribute available to do what you need.

Add a Test Button

Your own JavaScript functions will execute on events within your pages, but to demonstrate add the following button to your page:

The button passes the element ID as parameter, so that the JavaScript function can refer to it and access its custom attribute.

Get the Attribute

The most common way to access attributes in JavaScript is using “getAttributes” which is what we’ll do first. Add the following function in the script section of your page head:

function getElementAttribute(elemID)

We alert the attribute value for demonstration, but your own scripts can do whatever you need with it.

Get the Dataset

As an alternative to the DOM “getAttributes” method, you can use the element dataset. This can be more efficient, particularly in cases where your code is iterating through a variety of attributes. However, browser support for dataset is still very low, so do bear this in mind. This code carries out the same process as the line commented out from the previous approach:

//var theAttribute = theElement.getAttribute('data-product-category'); var theAttribute = theElement.dataset.productCategory;

With dataset you remove the “data-” from the start of the attribute name when referring to it in JavaScript – you do still need to include it in your HTML though. Notice that if your custom attribute name has a hyphen in it, which ours does, this becomes camel-case when accessed through the dataset (“data-product-category” becomes “productCategory”).

Other Methods and Functions

We have explored getting attributes, but your scripts can also set and remove them. The following code demonstrates setting attributes using the standard JavaScript method and the dataset alternative:

//DOM method theElement.setAttribute('data-product-category', 'sale'); //dataset version theElement.dataset.productCategory = "sale";

To remove an attribute, you can also use either a DOM method or the dataset:

//DOM method theElement.removeAttribute('data-product-category'); //dataset version theElement.dataset.productCategory = null;

Conclusion

Implementing custom attributes in HTML5 is not technically complex in itself, however the real difficulty is in choosing whether it is appropriate to use them in your own projects, and if so how to go about it efficiently. Finally, do remember that it’s still a little early to start using the dataset approach for functions your pages rely on, so be sure to provide an alternative for non-supporting browsers.

Sue Smith works as a Web/ software developer and technical writer based in the UK: see benormal.info for details. Sue has written for various clients including Smashing Magazine and Mobiletuts+. She also does a little Android development and some comedy writing. More articles by Sue Smith

Источник

Custom attributes

Use custom attributes to define characteristics of an HTML element.

This video features a third-party integration, and the UI may not be up to date. Visit their documentation for up-to-date info!

HTML attributes define characteristics (i.e., the behavior or appearance) of an HTML element. For example, class is an HTML attribute that provides a way to classify similar elements, and is used with CSS to add styles to elements which share that class. href is another HTML attribute which defines a link’s destination URL.

You can create some HTML attributes using native Webflow elements, styles, and settings (e.g., links, classes, ids, etc.). You can create others using custom attributes, which are valuable for a number of use cases — creating tooltips, improving your site’s accessibility with ARIA attributes, expanding custom code and page styling capabilities with CMS data, and more.

In this lesson, you’ll learn:

Note: Some custom attributes are reserved, as you can already create them using native Webflow elements, styles, and settings. For example, you can’t add href as a custom attribute to an existing element to make it behave like a link, but you can set a link destination URL on link elements using link settings.

How to create custom attributes

To create a new custom attribute:

  1. Select the element for which you want to create a custom attribute
  2. Go to Element settings panel >Custom attributes
  3. Click the “plus” icon
  4. Enter the name of your custom attribute (e.g., title, aria-label, etc.) along with its value
Pro tip: You can view a complete list of HTML attributes in the Mozilla HTML attribute reference.

A new custom attribute being created in the Custom attributes section of the Element settings panel. Its name is “title” and its value is “I’m a tooltip.”

How to use CMS data in custom attributes

You can connect your CMS data to custom attributes to bridge the gap between design, code, and dynamic data — and enable more power and flexibility in your design. This lets you control integrations or widgets that use HTML data attributes (e.g., maps or social widget previews), use custom CSS to customize page styling based on the value of a CMS field, improve site accessibility by using CMS data to populate ARIA attributes, and more.

Important: You can only connect CMS data to custom attributes on Collection pages or within Collection lists.

To connect your CMS data to custom attributes:

  1. Select the element for which you want to create a custom attribute
  2. Go to Element settings panel >Custom attributes
  3. Click the “plus” icon
  4. Enter the name of your custom attribute (e.g., title, aria-label, etc.)
  5. Click the purple “dot” icon in the Value field
  6. Choose the CMS field you want to connect to your custom attribute
Pro tip: You can also bind your CMS data to ID attributes, which are managed separately from custom attributes in the Element settings panel. This lets you create unique IDs to identify specific CMS items, which you can use to target those items with custom code.

A new custom attribute is bound to a “Name” Collection field from a Collection called “Blog posts.”

How to use component properties in custom attributes

You can also connect custom attributes to component properties. You can use these, for example, to enable and manage complex styling with custom code and CMS fields. Learn more about component properties.

To connect component properties to custom attributes:

  1. Edit the main component that contains the element for which you want to create a custom attribute
  2. Select the element for which you want to create a custom attribute
  3. Go to Element settings panel >Custom attributes
  4. Click the “plus” icon
  5. Enter the name of your custom attribute (e.g., title, aria-label, etc.)
  6. Click the purple “dot” icon in the Value field
  7. (Optional) Create a new component property
  8. Choose the component property you want to connect to your custom attribute

How to manage custom attributes

To edit a custom attribute:

  1. Select the element for which you want to edit a custom attribute
  2. Go to Element settings panel >Custom attributes
  3. Click the custom attribute you want to edit
  4. Update the name and/or value of the custom attribute

To delete a custom attribute:

  1. Select the element for which you want to delete a custom attribute
  2. Go to Element settings panel >Custom attributes
  3. Click the “trash” icon next to the custom attribute you want to delete

Источник

Оцените статью