411

Can I add a custom attribute to an HTML tag like the following?

<tag myAttri="myVal" />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lovespring
  • 19,051
  • 42
  • 103
  • 153
  • 3
    http://stackoverflow.com/questions/432174/how-to-store-arbitrary-data-for-some-html-tags – Tamas Czinege Nov 14 '09 at 22:48
  • 2
    and also http://stackoverflow.com/questions/209428/non-standard-attributes-on-html-tags-good-thing-bad-thing-your-thoughts – Tamas Czinege Nov 14 '09 at 22:49
  • possible duplicate of [Custom attributes - Yea or nay?](http://stackoverflow.com/questions/992115/custom-attributes-yea-or-nay) – Ciro Santilli OurBigBook.com Jan 31 '14 at 10:41
  • Though the answers say "yes," make sure you have a themed set of attributes that arent likely to be used with plug-ins. eg: "data-myuniqueattribute." I usually just prefix anything after "data-" with some type of two letter abbreviation. eg: "data-yscolumntype." Keep it unique. –  Dec 08 '16 at 17:32
  • MDN has a good resources for data-attributes, can refer for more info: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes – Wasit Shafi Oct 17 '21 at 19:31

18 Answers18

355

You can add custom attributes to your elements at will. But that will make your document invalid.

In HTML 5 you will have the opportunity to use custom data attributes prefixed with data-.

whyer
  • 783
  • 5
  • 16
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 208
    Remember "invalid" means nothing. The page will render fine 100% of the time. – John Farrell Nov 14 '09 at 20:54
  • 31
    Actually "invalid" has very real-world implications. E.g. it can put your document into quirksmode rendering. At any rate, use the HTML5 doctype and you'll be valid. – brentonstrine Aug 22 '13 at 19:39
  • There is a good table of different doctypes and corresponding browser modes here: https://hsivonen.fi/doctype/#handling. HTML5 doctype switches all post-2001 browsers into (Full) Standards mode. XHTML Transitional and HTML 4 Transitional (especially without DTD) doctypes do not:) – Ilya Streltsyn Aug 26 '14 at 20:23
  • holy sweet christ, thank you. @jfar right but it decreases readability. – Nevermore Oct 25 '17 at 11:25
  • My document is invalid anyways, because it tells me `|` is not allowed in a css `href`, but that's what's necessary for Google Fonts – Post Self Mar 24 '18 at 15:05
  • @kim366 I suggest \escaping the `|` like so: `\|` – George Mar 28 '18 at 03:23
  • @Noface interesting solution, I was thinking about urlencoding it to `%7C` – Post Self Mar 28 '18 at 07:03
  • @Noface Ah, nice. I'm actually using pug, not HTML, and the backslash seems to have zero effect on the resulting HTML code – Post Self Mar 28 '18 at 07:05
  • @Noface There we go: `href='https://fonts.googleapis.com/css?family=Some+Font|Another+Font|Third+Font'.replace(/\|/g, '%7C')` – Post Self Mar 28 '18 at 07:11
  • great. i recommend precompiling your template to html wherever possible as it will load faster and hit your server less. – George Mar 28 '18 at 10:16
  • The link has been changed. It is now : https://html.spec.whatwg.org/#embedding-custom-non-visible-data-with-the-data-*-attributes – Vincent Jan 10 '20 at 20:08
199

You can amend your !DOCTYPE declaration (i.e. DTD) to allow it, so that the [XML] document will still be valid:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
  <!ATTLIST tag myAttri CDATA #IMPLIED>
]>

#IMPLIED means it is an optional attribute, or you could use #REQUIRED, etc.

More information is in DTD - Attributes.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
carillonator
  • 4,715
  • 3
  • 29
  • 39
  • Need I create a DTD file or just add ATTLIST inline in html file? – lovespring Nov 15 '09 at 03:31
  • 2
    just put all that at the top of your html file (assuming xhtml 1.0 transitional is ok) – carillonator Nov 15 '09 at 22:19
  • 8
    Maybe I am missing something, but if you follow this approach, the ]> shows up in the rendered web page. Happening to me on Firefox 3.6. This snippet from http://www.alistapart.com/articles/customdtd/ seems to verify this behavior: "If you download the sample files for this article and validate file internal.html, you can see this for yourself. Unfortunately, when you display the file in a browser, the ]> shows up on the screen. There’s no way around this bug, so this approach is right out." – Mike Mar 25 '11 at 14:01
  • 4
    A couple of things that could help with the "]>" appearances: Save the file with a .xhtml filename extension. Include the MIME type in the file with ``. – Mr. Lance E Sloan Jun 04 '13 at 12:42
  • @LS I have same problem but after adding MIME type still getting `"]>"` character in body. – zur4ik Aug 03 '13 at 17:56
  • 4
    Declaring the attribute is pointless as far as browser behavior is considered. They do not read the DTD. Moreover, they cannot even properly skip the internal subset (which is used here), which explains the “]>” meass. The declaration would be relevant to formal validation only, and should not be used on production pages. – Jukka K. Korpela Aug 07 '13 at 21:01
  • Yes got the same problem - `]>`. So is there any way to make it valid without DTD or with default DTD (whatever it is in Chrome) – Flash Thunder Aug 22 '13 at 13:19
  • 38
    This answer only applies to XHTML and HTML 4.01 and older. It completely misses that you can now create your own attributes if you prefix them with `data-`. – brentonstrine Aug 22 '13 at 19:38
  • 1
    Remember that you're not serving XHTML unless your webserver is sending the document as XHTML (`application/xhtml+xml`) in the header. Most people that use the XHTML doctype only do so to put the browser into standards mode and aren't *really* serving XHTML to the browser, but HTML instead. – Cypher Nov 11 '13 at 19:52
  • i added this already. but my problem is my custom attribute has a capital letter in it and when i create the element with the custom attribute it is all lower case. how come? – Noah Passalacqua Apr 04 '14 at 08:54
  • @NoahPassalacqua that is expected behavior see http://w3c.github.io/html/single-page.html#embedding-custom-non-visible-data-with-the-data-attributes – Chiwda Jan 17 '17 at 22:58
  • Does this allow accessing via JavaScript? – Aaron Franke Dec 06 '19 at 09:36
90

No, this will break validation.

In HTML 5 you can/will be able to add custom attributes. Something like this:

<tag data-myAttri="myVal" />
  • 12
    but, I don't care validation, I just wanna it could be accessed by javascript. – lovespring Nov 14 '09 at 19:09
  • 12
    It will work of course. But deliberately creating invalid documents is not such a good idea. –  Nov 14 '09 at 19:12
  • 1
    Well technically it's not html any more. Equally you could add a load of binary in the middle of a tag - but it won't be html. – Draemon Nov 14 '09 at 19:13
  • While you can, you have to ask yourself if there is a better way to accomplish what you need. Why do you need to set custom attributes to access it in Javascript? – Vincent Ramdhanie Nov 14 '09 at 19:16
  • 37
    Creating invalid documents is a great idea. Google creates them to reduce load times, every site using canvas uses them to create a better user experience, and using javascript frameworks to pull meaningful data off of html elements is much easier using the custom attribute technique. – John Farrell Nov 14 '09 at 20:57
  • 4
    @jfar: Canvas is not invalid. It's not in HTML 4.01; however, it is a perfectly legal part of the upcoming HTML5 specification. – bcat Nov 14 '09 at 22:19
  • 4
    What do you mean "not invalid"? Its not part of any accepted specification. How can something be valid against a specification that does not exist? – John Farrell Nov 15 '09 at 20:26
  • 3
    The spec mentions not to use upper case letters, so it'd be – Ska Mar 31 '17 at 08:32
34

The jQuery data() function allows you to associate arbitrary data with DOM elements. Here's an example.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Draemon
  • 33,955
  • 16
  • 77
  • 104
  • 2
    This is golden. – Trevor Wood Sep 23 '16 at 21:57
  • 1
    in case no jQuery library is loaded, it's easy in pure/vanilla javascript to use `Element.getAttribute()`, `Element.setAttribute()`, or `Element.dataset` https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset – izzulmakin Aug 03 '22 at 08:54
28

In HTML5: yes: use the data- attribute.

 <ul>
  <li data-animal-type="bird">Owl</li>
  <li data-animal-type="fish">Salmon</li>
  <li data-animal-type="spider">Tarantula</li>
</ul> 
Davide Andrea
  • 1,357
  • 2
  • 15
  • 39
  • 10
    Better authority:https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes – Zuks Aug 18 '18 at 20:42
22

Yes, you can do it!

Having the next HTML tag:

<tag key="value"/>

We can access their attributes with JavaScript:

element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter

Element.setAttribute() put the attribute in the HTML tag if not exist. So, you don't need to declare it in the HTML code if you are going to set it with JavaScript.

key: could be any name you desire for the attribute, while is not already used for the current tag. value: it's always a string containing what you need.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
IgniteCoders
  • 4,834
  • 3
  • 44
  • 62
13

var demo = document.getElementById("demo")
console.log(demo.dataset.myvar)
// or
alert(demo.dataset.myvar)
//this will show in console the value of myvar
<div id="demo" data-myvar="foo">anything</div>
Jasim Droid
  • 137
  • 1
  • 3
11

Yes, you can, you did it in the question itself: <html myAttri="myVal"/>.

luvieere
  • 37,065
  • 18
  • 127
  • 179
  • 2
    Depends on what you define HTML as. I think of HTML as a language based on SGML, with a specific set of elements and attributes. XHTML is a variant on XML, with a specific set of elements and attributes that's a lot like HTML's. When you use your own attributes, it is still SGML of XML, but no longer HTML of XHTML in my opinion. – Douwe Maan Nov 14 '09 at 19:57
  • Take it as an adhoc extension, not a standard in a strict sense, but a sort of an implementation of the requirement that it shouldn't fail parsing if it contains custom attributes. – luvieere Nov 14 '09 at 20:15
  • 2
    DouweM: Of course, there's always the HTML serialization of HTML5, which is neither SGML nor XML. – bcat Nov 14 '09 at 22:17
  • 2
    And you broke (invalidated) the document in the process. Not good practice. – carillonator Nov 14 '09 at 22:30
6

You can set properties from JavaScript.

document.getElementById("foo").myAttri = "myVal"
ewg
  • 319
  • 1
  • 3
  • 1
    That's just adding a variable attached to an element. That is not a custom attribute in the HTML. – Moss Sep 22 '21 at 05:00
4

Here is the example:

document.getElementsByTagName("html").foo="bar"

Here is another example how to set custom attributes into body tag element:

document.getElementsByTagName('body')[0].dataset.attr1 = "foo";
document.getElementsByTagName('body')[0].dataset.attr2 = "bar";

Then read the attribute by:

attr1 = document.getElementsByTagName('body')[0].dataset.attr1
attr2 = document.getElementsByTagName('body')[0].dataset.attr2

You can test above code in Console in DevTools, e.g.

JS Console, DevTools in Chrome

kenorb
  • 155,785
  • 88
  • 678
  • 743
4

use data-any , I use them a lot

<aside data-area="asidetop" data-type="responsive" class="top">
Erick Boileau
  • 478
  • 4
  • 14
4

Yes, you can use data-* attribute. The data-* attribute is used to store custom data private to the page or application.

<ul>
    <li data-pageNumber="1"> 1 </li>
    <li data-pageNumber="2"> 2 </li>  
    <li data-pageNumber="3"> 3 </li>  
</ul
kyun
  • 9,710
  • 9
  • 31
  • 66
3

With custom elements, it is common to add custom attributes without data- prefix.

Here is an example from HTML standard: Custom elements (note the country attribute):

<flag-icon country="nl"></flag-icon>

Another example from MDN Web Docs: Using custom elements (note the l and c attributes):

<custom-square l="100" c="red"></custom-square>
Mahozad
  • 18,032
  • 13
  • 118
  • 133
2

well! you can actually create a bunch of custom HTML attributes by disguising the data attributes in what you actually want.

eg.

[attribute='value']{
color:red;
}
<span attribute="value" >hello world</span>

It apparently works but that would invalidate your document, there is no need of using JScript for you to have custom attributes or even elements unless you have to, you just need to treat your new formulated(custom) attributes just the same way you treat your "data" attribute

Remember "invalid" does not mean anything. The document will load fine at all the time. and some browsers would actually validate your document only by the presence of DOCTYPE....., you actually know what I mean.

Abdulbasit
  • 534
  • 8
  • 13
1

Another approach, which is clean and will keep the document valid, is to concatenate the data you want into another tag e.g. id, then use split to take what you want when you want it.

<html>
<script>
  function demonstrate(){
    var x = document.getElementById("example data").querySelectorAll("input");
    console.log(x);
    for(i=0;i<x.length;i++){
      var line_to_illustrate = x[i].id  + ":" + document.getElementById ( x[i].id ).value;
      //concatenated values
      console.log("this is all together: " + line_to_illustrate); 
      //split values
      var split_line_to_illustrate = line_to_illustrate.split(":");
      for(j=0;j<split_line_to_illustrate.length;j++){
        console.log("item " + j+ " is: " + split_line_to_illustrate[j]);
      }      
    }
  }
</script> 

<body>

<div id="example data">
  <!-- consider the id values representing a 'from-to' relationship -->
  <input id="1:2" type="number" name="quantity" min="0" max="9" value="2">
  <input id="1:4" type="number" name="quantity" min="0" max="9" value="1">
  <input id="3:6" type="number" name="quantity" min="0" max="9" value="5">  
</div>

<input type="button" name="" id="?" value="show me" onclick="demonstrate()"/>

</body>
</html>
CAtoOH
  • 71
  • 1
  • 7
1

I can think of a handy use for the custom tag "init". Include a JavaScript expression that gets evaluated at document.onLoad() time and provides a value for the tag, e.g.

<p>&lt;p&gt;The UTC date is &lt;span init="new Date().toUTCString()"&gt;?&lt;/span&gt;.&lt;p&gt;</p>

Some boilerplate JavaScript code would scan all the tags in the DOM at document.onload() time looking for the init attributes, evaluating the expressions that they contain, and assigning them to the containing tag's innerHTML. This would give HTML some of the power of JSP, PHP etc. Currently we have to split the HTML markup and the JavaScript code that illuminates it. Bugs love split code.

Procrastinator
  • 2,526
  • 30
  • 27
  • 36
-1

You can add, but then you have to write a line of JavaScript code too,

document.createElement('tag');

to make sure everything fall in place. I mean Internet Explorer :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
defau1t
  • 10,593
  • 2
  • 35
  • 47
  • 4
    This would be relevant if the tag name is not known to IE. Here the issue is a custom attribute, not a custom tag; the word “tag” in `` here apparently means just any HTML tag. – Jukka K. Korpela Aug 07 '13 at 21:03
  • Doesn't this also invalidate XHTML (unless it's a recognised tag)? – Paul Oct 08 '15 at 13:49
  • The question asks about custom attributes, not custom elements. – Sean Dec 05 '20 at 00:11
-9

You can do something like this to extract the value you want from JavaScript instead of an attribute:

<a href='#' class='click'>
    <span style='display:none;'>value for JavaScript</span>some text
</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Frog
  • 9
  • 1