Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest self-service freelancing marketplace for people like you.

HTML <pre> data-* Attribute

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

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

Example

#

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

  SELECT FirstName, LastName
  FROM Customer ORDER BY LastName
<pre data-title="Customer names list">
  SELECT FirstName, LastName
  FROM Customer ORDER BY LastName
</pre>

Using data-*

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

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

An <pre> 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 pre.


Syntax

<pre 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-query attribute on a <pre> tag.
Clicking the button will display the query value.

  SELECT FirstName, LastName
  FROM Customer ORDER BY LastName

<pre id="mypre" data-query="Customer names">
  SELECT FirstName, LastName
  FROM Customer ORDER BY LastName
</pre>

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

<script>
  let show = () => {
    let element = document.getElementById("mypre");
    alert("Query = " + element.getAttribute('data-query'));
  }
</script>

Code explanation

The <pre> tag has a custom data-query attribute.

The data-query attribute sets the query of the preformatted text.

Clicks are handled by the onclick event.

Onclick invokes a JavaScript function that extracts and displays the <pre> query.

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


Browser support

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

Chrome
1.0 Sep 2008
Firefox
1.0 Sep 2002
IE/Edge
1.0 Aug 1995
Opera
1.0 Jan 2006
Safari
1.0 Jan 2003

You may also like

 Back to <pre>
Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest self-service freelancing marketplace for people like you.

Guides