Dofactory.com
Dofactory.com

HTML <nav> data-* Attribute

A data-* attribute on a <nav> tag attaches additional data to the navigation element.

To create a custom attribute, replace * with a lowercase string, such as data-id, data-status, or data-location.

Example

#

A custom data-navigation-type attribute on a <nav> element.
The attribute value is not visible, but it is readable by JavaScript.

<nav data-navigation-type="website main navigation">
  <a href="javascript:alert('Going to Introduction')">Introduction</a> <br />
  <a href="javascript:alert('Going to What Is HTML')">What is HTML</a>  <br />
  <a href="javascript:alert('Going to HTML Syntax')">HTML Syntax</a>  <br />
  <a href="javascript:alert('Going to HTML Elements')">HTML Elements</a>
</nav>

Using data-*

The data-* attribute adds custom information to a <nav> element.

The * part is replaced with a lowercase string, such as data-id, data-cost, or data-location.

An <nav> element can have any number of data-* attributes, each with their own name.

Using data-* attributes reduces the need for requests to the server.

Note: The data-* attribute is not visible and does not change the appearance of the nav.


Syntax

<nav data-*="value">

Note: The * can be any string, such as data-iddata-costdata-supplier,  etc.


Values

#

Value Description
value A string value. Can be numeric, alphanumeric, JSON, etc.

More Examples

A custom data-nav-type attribute on a <nav> tag.
Clicking the button will display the navigation type value.


<nav id="mynav" data-nav-type="Main navigation">
  <a href="javascript:alert('Going to Introduction')">Introduction</a> <br />
  <a href="javascript:alert('Going to What Is HTML')">What is HTML</a>  <br />
  <a href="javascript:alert('Going to HTML Syntax')">HTML Syntax</a>  <br />
  <a href="javascript:alert('Going to HTML Elements')">HTML Elements</a>
</nav>

<br/>
<button onclick="show();">Show data</button>

<script>
  let show = () => {
    let element = document.getElementById("mynav");
    alert("Navigation type = " + element.getAttribute('data-nav-type'));
  }
</script>

Code explanation

The <nav> tag has a custom data-navigation-type attribute.

The data-navigation-type attribute stores the type or purpose of the navigation.

Clicks are handled by the onclick event.

Onclick invokes a JavaScript function that extracts and displays the <nav> type.

Note: Notice how the type displays immediately without server call.


Browser support

Here is when data-* support started for each browser:

Chrome
6.0 Sep 2010
Firefox
4.0 Mar 2011
IE/Edge
9.0 Mar 2011
Opera
11.0 Dec 2010
Safari
5.0 Jun 2010

You may also like

 Back to <nav>

Author: Jack Poorte
Published: Jun 20 2021
Last Reviewed: Sep 30 2023


What's your favorite/least favorite part of Dofactory?


Guides