A data-* attribute on a <th> tag attaches additional data to the table header cell.
To create a custom attribute, replace * with a lowercase string, such as data-id
, data-status
, or data-location
.
A custom data-title
attribute on a <th> tag.
The attribute value is not visible, but is readable by JavaScript.
Full name | |
---|---|
Denice | Hobermann |
Paulo | Cornell |
<style>
table.tb { width: 250px; border-collapse: collapse; }
.tb th, .tb td { border: solid 1px #777; padding: 5px; }
.tb th { background-color:lightblue; text-align: center; }
</style>
<table class="tb">
<tr>
<th data-title="Customer full name" colspan="2">Full name</th>
</tr>
<tr>
<td>Denice</td>
<td>Hobermann</td>
</tr>
<tr>
<td>Paulo</td>
<td>Cornell</td>
</tr>
</table>
The data-* attribute adds custom information to a <th> element.
The * part is replaced with a lowercase string, such as data-id, data-cost, or data-location.
An <th> 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 th.
<th data-*="value">
Note: The * can be any string, such as data-id
, data-cost
, data-supplier
, etc.
Value | Description |
---|---|
value | A string value. Can be numeric, alphanumeric, JSON, etc. |
A custom data-title
attribute on a <th> element.
Clicking the button will display the title value.
Customer | |
---|---|
Denice | Hobermann |
Paulo | Cornell |
<style>
table.tb { width: 250px; border-collapse: collapse; }
.tb th, .tb td { border: solid 1px #777; padding: 5px; }
.tb th { background-color:lightblue; text-align: center; }
</style>
<table class="tb">
<tr>
<th id="myth" data-title="Customer name" colspan="2">Customer</th>
</tr>
<tr>
<td>Denice</td>
<td>Hobermann</td>
</tr>
<tr>
<td>Paulo</td>
<td>Cornell</td>
</tr>
</table>
<br/>
<button onclick="show();">Show data</button>
<script>
let show = () => {
let element = document.getElementById("myth");
alert("Title = " + element.getAttribute('data-title'));
}
</script>
The <th> tag has a custom data-title
attribute.
The data-title
attribute describes the content of the table header.
Clicks are handled by the onclick
event.
Onclick invokes a JavaScript function that extracts and displays the <th> title.
Note: Notice how the title displays immediately without server call.
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 |
Back to <th>